我有三个角色:1. Admin
2. Client
3.Store
我有三张桌子:1. users
2. roles
3.role_user
如何获取所有具有该角色的用户Client
?
我试过这个
$clients = User::roles()->where('App\Models\Role',Role::CLIENT)->get();
我收到以下错误。
不应静态调用非静态方法 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');
}
}
用户模型
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);
}
}