0

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?

Adam
  • 25,960
  • 22
  • 158
  • 247

1 Answers1

3

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

Mihir Bhende
  • 8,677
  • 1
  • 30
  • 37
  • Thanks for spotting the typo, I corrected it. I think your right when I would add the foreignt key it would work. However, I do not want to disable `only_full_group_by`. But thanks anyway – Adam Feb 03 '19 at 22:59