Eloquent many-to-many-to-many - how to load distant relation easily

前端 未结 2 965
长发绾君心
长发绾君心 2020-12-01 15:37

I have 3 tables; users, groups and permissions

In models I have the relationships set as belongsToMany in user model:

public function groups() {
            


        
相关标签:
2条回答
  • 2020-12-01 15:48

    This is how you can do it:

    User::where('id', $id)->with(['groups.permissions' => function ($q) use (&$permissions) {
         $permissions = $q->get()->unique();
    }])->first();
    
    // then
    $permissions; // collection of unique permissions of the user with id = $id
    
    0 讨论(0)
  • 2020-12-01 16:00

    It should look something like this if you are eager loading...

    $user = User::where('id', $id)->with(['groups.permissions'])->first();
    
    0 讨论(0)
提交回复
热议问题