Search code examples
laraveleloquentgroup-byeloquent-relationship

Retrieve grouped relation with Eloquent ORM


I have a relationship which looks like this:

User
 - id
Menu
 - id
 - appetizer_id
 - main_course_id
 - dessert_id
User_Menu
 - user_id
 - menu_id

and corresponding models:

class User
{
    public function menus()
    {
        return $this->belongsToMany('App\Models\Menu', 'user_menu', 'user_id', 'menu_id');
    }
}

class Menu 
{
    public function dessert()
    {
        return $this->belongsTo('App\Models\Dessert', 'dessert_id');
    }
}

In other words there are users and menus with a many to many relationship. Now I would like to retrieve all the distinct desserts for a given user. I've tried using group by, but it does not allow me to select and group by a single column, because the pivot columns are always included in the query:

$desserts = User::find(1)->menus()
    ->select('dessert_id')
    ->groupBy('dessert_id')
    ->with('dessert')
    ->get();

throws the following error:

'User_Menu.user_id' isn't in GROUP BY

Solution

  • $desserts = User::join('User_Menu', 'User.id', '=', 'User_Menu.user_id')
                    ->join('Menu', 'User_Menu.menu_id', '=','Menu.id')
                    ->get();