I know this question has be asked before here: Laravel Grouping by Eloquent Relationship but the answers are from 2016 and they seem not to work in 2019. Also my question is more simple, since I only need one relation level.
My Question
A
user has multiple items.
How to find how many items
a user has of each item_type
with one query?
This is what I tried:
A query like
User::with(['items' => function($q){
$q->groupBy('type');
});
returns this error:
Syntax error or access violation: 1055 Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'items.id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by
I tried to fix this error with the following query:
User::with(['items' => function($q){
$q->select('type', \DB::raw('count(*) as total'))
->groupBy('type');
});
However, this returns a collection of users
where each user's item
collection is empty.
Is it somehow possible to group by a relation in the query?