如何在 Laravel 中过滤多对多结构
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21378889/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to filter many to many structure in Laravel
提问by Chan
I got a many to many user and role structure
我有一个多对多的用户和角色结构
users
id
name
用户
ID
名称
roles
id
name
角色
ID
名称
role_user
user_id
role_id
role_user
user_id
role_id
Model
模型
User.php
用户名.php
public function roles() {
return $this->belongsToMany('Role');
}
Role.php
角色.php
public function users() {
return $this->belongsToMany('User');
}
There are two data admins
and members
in roles table, I would like to know to to filter users which role is admins.
有两个数据admins
,members
在角色表中,我想知道过滤用户哪个角色是管理员。
回答by user1669496
This should give you all users who are admins.
这应该为您提供所有管理员用户。
$users = User::whereHas('roles', function($q) {
$q->where('name', '=', 'admins');
})->get();
You can see more information on the has()
method at http://laravel.com/docs/eloquent#querying-relations
您可以has()
在http://laravel.com/docs/eloquent#querying-relations上查看有关该方法的更多信息