[英]laravel retrieve all users where value match pivot table
因此,我試圖建立user
roles
和profiles
之間的關系一切都在創建時工作,但我不知道如何過濾我想要按特定角色或配置文件列出用戶。
這是我現在的表格結構。 每個表都對應於它的模型,因此表users
具有模型User
表roles
具有模型Role
並且存在用於連接具有角色的用戶的數據透視表role_user
。
這將是角色表
+----+----------+---------------+
| id | name | Description |
+----+----------+---------------+
| 1 | admin | Administrator |
| 2 | client | Client |
| 3 | operator | Operator |
+----+----------+---------------+
這將是用戶角色的數據透視表
+----+---------+---------+
| id | user_id | role_id |
+----+---------+---------+
| 1 | 1 | 3 |
| 2 | 2 | 1 |
+----+---------+---------+
這通常是用戶表
+----+--------+-----------------+
| id | name | Email |
+----+--------+-----------------+
| 1 | Mario | mario@email.tld |
| 2 | Luighi | lui@email.tld |
+----+--------+-----------------+
所以,如果我列出所有非常簡單的帳戶,就像我會使用的那樣
public function index(Request $request)
{
$users = User::get();
return view('users/index', compact('users'));
}
如果我想按特定名稱或電子郵件過濾用戶,我只會過濾
$users = User::where('name', 'Mario')->get();
這將檢索匹配名稱為mario的所有用戶。
現在更復雜的是我偶然發現的東西,我無法在互聯網上找到答案。
我想檢索其中來自數據透視表的用戶角色與角色表中的角色匹配的所有用戶。
例子是
Retrieve All Users WHERE (pivot table) role_user EQUALS name OPERATOR from role table
那將返回用戶Mario,因為他的用戶id是1,並且在數據透視表中user_id匹配role_id 3,在角色表中,角色名為OPERATOR。
您可以通過將用戶表連接到數據透視表並過濾role_id = operator_id的位置來實現
$operator_id =
DB::table('roles')->where('name','=','operator')->first()->id;
DB::table('users') ->join('pivot', function ($join)
{ $join->on('users.id', '=', 'pivot.user_id') ->where('pivot.role_id',
'=', $operator_id); }) ->get();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.