[11.x] Support DB aggregate by group #53209
Open
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.
Currently, the aggregate methods ignore the
group by
clause. This PR change the result ofto return a Collection of
[role, count]
instead of a single total count.Result before:
40
Result after:
The aggregate result is always in a column named
aggregate
and the "group by" columns are added to the result.Why?
I'm implementing
withCount
for MongoDB models and hybrid MongoDB to SQL models. This implementation is done duringeagerLoad
by doing a count by foreign key in the related table (i.e.select foreign_id, count(*) from mytable where foreign_id in (1,2,3) group by foreign_id
). I managed to do that for MongoDB, and this PR makes it work for hybrid MongoDB to SQL models.Union and group by
This also works with unions. I have to change the generated SQL to apply the
group by
clause to the union result instead of the first query of the union.For the following query:
The generated SQL is before/after the PR:
If anyone need to generate the previous SQL, the query builder for the 1st subquery would have to be wrapped:
Return type of count/sum/avg/min/max
The return type of the aggregate methods indicate that a single value is expected: the result of the aggregation. But since the group by clause is used, the result is a collection of
[...groups, aggregate]
. I had to change the return type in phpdoc to addCollection
. This may impact thecount
function only, as other returnmixed
that already includesCollection
.An alternative could have been to add a new methods
sumBy($function, $column, ...$groups)
but I think this is already the role of->groupBy(...$groups)
to specify the expected groups.