【发布时间】:2020-02-11 22:34:13
【问题描述】:
我有两个模型,用户和角色。每个用户都有许多角色,如“管理员”、“简单用户”等。 我想获取所有没有“管理员”角色的用户。我知道这可以通过加入查询来解决。但我想使用“wherHas()”函数。
User table has id, name
Role table has id, slug, name
user_role as pivot table has user_id and role_id
在用户模型中
public function roles()
{
return $this->belongsToMany('App\Role');
}
在角色模型中
public function users()
{
return $this->belongsToMany('App\User');
}
查询示例:
$users = User::whereHas('roles', function ($query){
$query->where('slug', '!=', 'ecoyar');
})->get();
对不起我的英语!
【问题讨论】:
-
您需要提供更多细节:这两个模型是如何联系起来的?每个模型中有哪些列?为什么你不能只做
$users = User::where('role', '!=', '1)->get()? -
我根据我的情况更新了我的问题。
标签: laravel