为什么我的模型在关系子查询上看不到 spatie 权限特征方法?

Why my model can't see spatie permissions trait method on relationship subquery?

我在 laravel 项目中使用 spatie/laravel-permissions composer 包。 当我 运行 这个查询时:

$jobs = Job::whereIn('id', $ids)->whereHas('user', function ($query) {
    $query->hasRole('company');
})->get();

Return 错误信息

Call to undefined method Illuminate\Database\Eloquent\Builder::hasRole()

如何解决我的问题?

因为传递给函数闭包的 $user 是查询构建器实例而不是 User 模型的实例,所以在上面声明 $user 的地方,请确保获取实例

$user = User::where(......, ........)->first(); // Without first() it's a query builder
$jobs = Job::whereIn('id', $ids)->whereHas('user', function ($user) {
    $user->hasRole('company');
})->get();

hasRole-method 不是作用域,不能用于 Builder 实例。

我认为您应该能够在您的应用程序中使用 role-scope

$jobs = Job::whereIn('id', $ids)->whereHas('user', function ($q) {
    return $q->role('company');
})->get();