雄辩的“多对多” - 如何容易地加载遥远的关系 [英] Eloquent many-to-many-to-many - how to load distant relation easily
本文介绍了雄辩的“多对多” - 如何容易地加载遥远的关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在模型中,我将用户模型中的关系设置为belongsToMany
:
public function groups(){
return $ this-> belongsToMany('Group');
}
在组模型中:
public function users(){
return $ this-> belongsToMany('User');
}
public function permissions(){
return $ this-> belongsToMany('Permission');
}
在权限模型中:
公共功能组(){
return $ this-> belongsToMany('Group','id');
}
许多用户 - 到许多组
许多组 - 许多权限
我正在尝试获取用户拥有的所有权限,并且不知道它的代码应该是什么样的。任何人都可以帮忙?
解决方案
这是你可以这样做的:
User :: where('id',$ id) - > with(['groups.permissions'=> function($ q)use(& $ permissions)
$ permissions = $ q-> get() - > unique();
}]) - > first();
// then
$ permissions; //用id = $ id
收集用户的唯一权限
I have 3 tables; users, groups and permissions
In models I have the relationships set as belongsToMany in user model:
public function groups() {
return $this->belongsToMany('Group');
}
in group model:
public function users() {
return $this->belongsToMany('User');
}
public function permissions() {
return $this->belongsToMany('Permission');
}
in permissions model:
public function groups() {
return $this->belongsToMany('Group', 'id');
}
many users - to - many groups many groups - to - many permissions
I'm trying to get all the permissions a user has, and have no clue what the code for it should look like. Can anyone help?
解决方案
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
这篇关于雄辩的“多对多” - 如何容易地加载遥远的关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文