在我的User
课程中,我有以下关系:
/**
* Roles of a User
*
* @return \Illuminate\Database\Eloquent\Relations\hasManyThrough
*/
public function roles()
{
return $this->hasManyThrough(Role::class, UserRole::class, 'user_id', 'id');
}
我已经创建了一个方法来根据传入的角色返回布尔值:
/**
* Is User of a given Role?
*
* @return bool
*/
public function hasRole($roleShort = null)
{
if (!$roleShort) {
return false;
}
$result = $this->roles
->where('roles.short', '=', $roleShort)
->first();
return $result ? true : false;
}
在Tinker
中,我获得了第一个用户并返回了他的角色,并且按预期工作正常。但是当我将角色短名称传递给hasRole
方法时,它总是返回false。
>>> $u = User::find(1);
[!] Aliasing 'User' to 'App\Models\User' for this Tinker session.
=> App\Models\User {#839
id: 1,
uuid: "4e86a284-ae1f-4753-a243-797dc5ce98fc",
name: "Test User",
email: "mytest@myapp.com",
country_id: 11,
partner_id: null,
region_id: 1,
language_id: 1,
time_zone_id: 387,
date_format_id: 1,
time_format_id: 11,
date_time_format_id: 13,
activated_at: "2018-04-01 14:00:00",
deleted_at: null,
created_at: "2018-04-01 22:53:32",
updated_at: "2018-04-01 22:53:32",
}
>>> $u->roles
=> Illuminate\Database\Eloquent\Collection {#820
all: [
App\Models\Role {#827
id: 1,
partner: 0,
name: "Admininstrator",
short: "ADMIN",
user_id: 1,
},
],
}
>>> $u->hasRole('ADMIN');
=> false
我错过了什么?我尝试记录SQL查询但出现以下错误:
Log::info($this->roles
->where('roles.short', '=', $roleShort)
->first()
->toSql());
>>> $u->hasRole('ADMIN');
PHP Error: Call to a member function toSql() on null in /home/vagrant/src/sdme/app/Models/User.php on line 126
答案 0 :(得分:1)
您正在查询错误的属性。您的属性为src
而不是short
。
此外,您可以使用roles.short
方法获取exists()
结果。
boolean
您还在/**
* Is User of a given Role?
*
* @return bool
*/
public function hasRole($roleShort = null)
{
if (! $roleShort) {
return false;
}
return $this->roles()->where('short', $roleShort)->exists();
}
上调用了where()
和toSql()
,而不是Collection
个实例。请注意我的答案中Query\Builder
之后的括号 - roles
。