2017-06-26 26 views
2

我有一個users表和兩個數據透視表(user_locations,user_roles),它允許用戶關聯多個「位置」和「角色」。選擇屬於New York(某個位置)的用戶的最佳方式是什麼?Manager(角色)?MySQL/Laravel/Eloquent:選擇存在於兩個表中的行

列在每個表中:

users =>idname

user_locations =>user_idlocation_id

user_roles =>user_idrole_id

因此,例如,我想要獲取與location_i關聯的用戶列表d 100和role_id 200

我希望我明確地解釋我的目標。先謝謝你!

回答

2

如果您在用戶模式有正確的關係設置,你可以這樣做:

$new_york_managers = User::whereHas('locations', function($q) { 
    $q->where('id', 100); 
})->whereHas('roles', function($q) { 
    $q->where('id', 200); 
}); 
+0

該訣竅。非常感謝! –