![](/img/trans.png)
[英]Many-to-many SQL relation: how to retrieve all related entries in one query?
[英]How to get all users with all their roles in a many to many relation based sql query?
目標
獲取具有所有角色的所有用戶。
問題
如果一個用戶擁有多個角色,我會為他擁有的每個角色獲取該用戶的一個實例。
描述
我有一個包含三個表的設置,例如在這個 stackoverflow 帖子中描述的那樣。 一個user
表、一個role
表和一個role_user
用戶表。 現在我想用這個查詢查詢所有用戶的角色:
$allUsers = DB::table('users')
->join('role_user', 'role_user.user_id', '=', 'users' . '.id')
->join('roles', 'roles.id', '=', 'role_user.role_id')
->select(['users.uuid', 'users.username', 'users.last_online_at', 'roles.role', 'roles.id as role_id'])
->get();
對我來說,它看起來就像簡單的 MYSQL 查詢提案,它使 Lizesh Shakya 在我上面已經提到的 stackoverflow 帖子的第二個帖子中。 除了我使用 Laravel 之外。 而且我知道,我可以使用用戶 model 解決它,並在其中設置適當的belongsToMany
方法和角色 model。 但我想更深入地理解它,因此我嘗試那樣做。 例如,如果我有三個用戶並且如果一個用戶具有角色“編輯”和“作者”,則查詢將返回四個用戶。 每個角色一個。
Illuminate\Support\Collection {#1267 ▼
#items: array:4 [▼
0 => {#1273 ▼
+"uuid": "fc8bbd29-9005-4f05-9706-a437933d3bc2"
+"username": "admin"
+"last_online_at": "2021-01-16 19:01:37"
+"role": "admin"
+"role_id": 1
}
1 => {#1272 ▼
+"uuid": "d957e5af-f8f3-4a07-a2c3-eabecbdda618"
+"username": "author1"
+"last_online_at": "2021-01-16 19:01:37"
+"role": "author"
+"role_id": 3
}
2 => {#1282 ▼
+"uuid": "dc94d900-bbaf-4605-b8d8-6bab5fb43b70"
+"username": "editor"
+"last_online_at": "2021-01-16 19:01:37"
+"role": "editor"
+"role_id": 2
}
3 => {#1281 ▼
+"uuid": "d957e5af-f8f3-4a07-a2c3-eabecbdda618"
+"username": "author1"
+"last_online_at": "2021-01-16 19:01:37"
+"role": "editor"
+"role_id": 2
}
]
}
那么我的錯在哪里? :)
因此,如果我理解正確,您想要一個用戶列表及其角色嗎?
在您的用戶控制器上:
public function getUsersWithRoles(){
$all_users = User::all()->load('roles');
$body = compact('all_users');
return response()->json(compact('body'));
}
或者
public function getUsersWithRoles(){
$all_users = User::with('roles')->get();
$body = compact('all_users');
return response()->json(compact('body'));
}
不要忘記在模型中聲明您的關系。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.