From this question: How to GROUP and SUM a pivot table column in Eloquent relationship?
I used this code in my User
Model:
public function teams() {
return $this->belongsToMany('App\Models\Team', 'team_members', 'user_id', 'team_id')
->groupBy('pivot_team_id');
}
I wanted to use ->groupBy()
because in my team
s, a single user
can act as multiple team_member
s for different roles. I do not want team
records duplicate.
But when I try to access e.g. with this code on my page dd(Auth::user()->teams)
, Laravel threw the following exception:
SQLSTATE[42000]: Syntax error or access violation: 1055 'laravel.teams.id' isn't in GROUP BY (SQL: select `teams`.*, `team_members`.`user_id` as `pivot_user_id`, `team_members`.`team_id` as `pivot_team_id` from `teams` inner join `team_members` on `teams`.`id` = `team_members`.`team_id` where `team_members`.`user_id` = 3 group by `pivot_team_id`)
Then I tried running that exact same SQL in the error by myself, it worked:
Why is that so? And where did I get it wrong?