简体   繁体   中英

Laravel Group & Count by Eloquent Relationship

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?

There is an error :

You are using $q as closure argument and inside you are using $query. Also sometimes I have faced issue where I had to pass the foreign key inside the relation query closure to get the results :

<?php 

$userWithItems = User::with(['items' => function($q){
    $q->select('type', \DB::raw('count(*) as total'), 'user_id')
          ->groupBy('type');
});

Try it once by removing user_id if it works then it's better. Secondly you can not select non aggregated columns in mysql when you have groupby. The option is disable only_full_group_by in mysql configurations. So mostl likely user_id will also fail unless you disable this configuration

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM