[9.x] Fix issue with aggregates (withSum, etc.) for pivot columns on self-referencing many-to-many relations #44286
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
An SQL error currently occurs when trying to run any
withX
aggregate functions on a column from a pivot table for a many-to-many relation that references the same table. The error that occurs is similar to the below:The issue at hand is from lines 625–627 in QueriesRelationships:
The condition in this ternary checks whether the current query references the same table as the relation's query, and if so, it prepends a "relationCountHash" which in the above error is
"laravel_reserved_0"
. In a many-to-many relationship which references the same table, for example a "friends" relationship which links from ausers
table to theusers
table, this would return true and it would make referencing columns from a pivot table impossible in this situation.My proposed fix for this is to move the above logic into a new method which checks for a period (
.
) in the$column
, to see if the referenced column is on a different table to the original query. If this is the case, it just returns the$column
, without the reserved table alias.This shouldn't, to my knowledge, introduced any breaking changes with current versions as any columns passed in with a period are automatically escaped into
"table_name"."column"
syntax, rather than treated as a single column (e.g."table_name.column"
.