本文介紹了Eloquent 多對多對多 - 如何輕松加載遠距離關系的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我有 3 張桌子;用戶、組和權限
I have 3 tables; users, groups and permissions
在模型中,我將關系設置為belongsToMany在用戶模型中:
In models I have the relationships set as belongsToMany in user model:
public function groups() {
return $this->belongsToMany('Group');
}
在組模型中:
public function users() {
return $this->belongsToMany('User');
}
public function permissions() {
return $this->belongsToMany('Permission');
}
在權限模型中:
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?
推薦答案
您可以這樣做:
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
這篇關于Eloquent 多對多對多 - 如何輕松加載遠距離關系的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!