我一直在努力想象是否有可能在Eloquent中实现基于查询的属性,例如以下数据结构允许在User模型上具有is_admin
属性,该属性返回{{1 }或true
取决于是否为用户分配了名为false
的角色。
由于某种意义上的关系是这样的,我认为这是可能的,但是我究竟是如何做到的。
Admin
答案 0 :(得分:0)
这是未经测试的代码,但我很确定它会起作用:
class User extends Eloquent {
public function roles()
{
return $this->belongsToMany('Role', 'user_roles');
}
public function hasRole($roleName)
{
return count($this->roles()->where('name',$roleName)->get()) > 0;
}
}
然后使用它:
$user = User::find(1);
if ($user->hasRole('Amdin'))
{
/// do something
}
答案 1 :(得分:0)
不是一个属性,但您可以在User中实现$ user-> isAdmin()方法,如下所示:
public function isAdmin()
{
// check if the user has an admin role
if ($this->roles()->where('name', '=', 'Admin')->count() > 0)
{
// return true if he does
return true;
}
// return false if he doesn't
return false
}
或者,你可以在User表中创建一个'is_admin'列作为整数,长度为1.设置默认值为0,如果用户管理员设置为1,那么你可以使用$ user-> is_admin在布尔测试中。