Php Laravel 5.6不返回数据的雄辩方法
在我的Php Laravel 5.6不返回数据的雄辩方法,php,laravel-5.6,Php,Laravel 5.6,在我的User课程中,我有以下关系: /** * Roles of a User * * @return \Illuminate\Database\Eloquent\Relations\hasManyThrough */ public function roles() { return $this->hasManyThrough(Role::class, UserRole::class, 'user_id', 'id'); } 我创建了一个基于传入角色返回布尔值的方法:
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
您正在查询不正确的属性。您的属性是
short
而不是角色。short
此外,您还可以使用exists()
方法获得布尔值结果
/**
* 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()
,而不是Query\Builder
实例。注意我的回答中roles
后面的括号-roles()
嘿@fubar,你太棒了!谢谢你的课!