Kis*_*dar 0 php laravel laravel-6
我有三个角色:1. Admin2. Client3.Store
我有三张表:1. users2. roles3.role_user
我怎样才能获得所有拥有该角色的用户Client?
我试过这个
$clients = User::roles()->where('App\Models\Role',Role::CLIENT)->get();
Run Code Online (Sandbox Code Playgroud)
我收到以下错误。
不应静态调用非静态方法 App\Models\User::roles()
好榜样
class Role extends Model
{
public const ADMIN = 'Admin';
public const CLIENT = 'Client';
public const STORE = 'Store';
public function users()
{
return $this->belongsToMany('App\Models\User')->using('App\Models\UserRole');
}
}
Run Code Online (Sandbox Code Playgroud)
用户模型
class User extends Authenticatable
{
use Notifiable;
protected $fillable = [
'name',
'first_name',
'last_name',
'email',
'password',
'activated',
'token',
'signup_ip_address',
'signup_confirmation_ip_address',
'signup_sm_ip_address',
'admin_ip_address',
'updated_ip_address',
'deleted_ip_address',
];
protected $hidden = [
'password', 'remember_token',
];
protected $casts = [
'email_verified_at' => 'datetime',
];
public function hasRole(String $roleName)
{
return $this->roles()->where('name', $roleName)->exists();
}
public function roles()
{
return $this->belongsToMany('App\Models\Role');
}
public function addRole(String $roleName)
{
$role = Role::where('name', $roleName)->first();
if ($role) $this->roles()->save($role);
}
}
Run Code Online (Sandbox Code Playgroud)
你可以用whereHas()方法来做。这是一种exists在查询中使用关系条件的方法
$clients = User::whereHas('roles', function($role) {
$role->where('name', '=', Role::CLIENT);
})->get();
Run Code Online (Sandbox Code Playgroud)
如果你也想获得角色,堆叠with()方法
$clients = User::whereHas('roles', function($role) {
$role->where('name', '=', Role::CLIENT);
})->with(['roles' => function($role) {
$role->where('name', '=', Role::CLIENT);
}])->get();
Run Code Online (Sandbox Code Playgroud)