我有用户,角色和role_user表。
User.php
public function roels()
{
return $this->belongsToMany('Role');
}
Role.php
public function users()
{
return $this->belongsToMany('User');
}
用户可能有许多角色,例如admin,sub-admin,member,如何按角色列出用户(如all admin或all sub-admin)?
有很多方法。尝试这个:
$admins = User::whereHas('roles', function ($q) {
$q->where('roles.name', '=', 'admin'); // or whatever constraint you need here
})->get();
要么:
$adminRole = Role::where('name', 'admin')->first();
$admins = $adminRole->users;
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句