Skip to content

Commit

Permalink
[9.x] Fix issue with aggregates (withSum, etc.) for pivot columns on …
Browse files Browse the repository at this point in the history
…self-referencing many-to-many relations (#44286)

* Add failing test for current state.

* Apply potential fix.

* Potential fix?

* Use better name
  • Loading branch information
kayrunm authored Oct 4, 2022
1 parent d0d5e23 commit b88e268
Showing 1 changed file with 19 additions and 3 deletions.
22 changes: 19 additions & 3 deletions Eloquent/Concerns/QueriesRelationships.php
Original file line number Diff line number Diff line change
Expand Up @@ -622,9 +622,7 @@ public function withAggregate($relations, $column, $function = null)
$relation = $this->getRelationWithoutConstraints($name);

if ($function) {
$hashedColumn = $this->getQuery()->from === $relation->getQuery()->getQuery()->from
? "{$relation->getRelationCountHash(false)}.$column"
: $column;
$hashedColumn = $this->getRelationHashedColumn($column, $relation);

$wrappedColumn = $this->getQuery()->getGrammar()->wrap(
$column === '*' ? $column : $relation->getRelated()->qualifyColumn($hashedColumn)
Expand Down Expand Up @@ -680,6 +678,24 @@ public function withAggregate($relations, $column, $function = null)
return $this;
}

/**
* Get the relation hashed column name for the given column and relation.
*
* @param string $column
* @param \Illuminate\Database\Eloquent\Relations\Relationship $relation
* @return string
*/
protected function getRelationHashedColumn($column, $relation)
{
if (str_contains($column, '.')) {
return $column;
}

return $this->getQuery()->from === $relation->getQuery()->getQuery()->from
? "{$relation->getRelationCountHash(false)}.$column"
: $column;
}

/**
* Add subselect queries to count the relations.
*
Expand Down

0 comments on commit b88e268

Please sign in to comment.