简体   繁体   English

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

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

I use spatie/laravel-permissions composer package in my laravel projects. 我在laravel项目中使用spatie / laravel-permissions作曲家软件包。 When I run this query: 当我运行此查询时:

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

Return error message 返回错误信息

Call to undefined method Illuminate\\Database\\Eloquent\\Builder::hasRole() 调用未定义的方法Illuminate \\ Database \\ Eloquent \\ Builder :: hasRole()

How I can fix my problem in my case? 我该如何解决我的问题?

The hasRole -method is not a scope and can't be used on a Builder instance. hasRole方法不是作用域,不能在Builder实例上使用。

I think you should be able to use the role -scope in your application. 我认为您应该能够在应用程序中使用role -scope

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

Because $user passed to the function closure is a query builder instance and not an instance of the User model so where you're declaring the $user above, make sure to get an instance 由于传递给函数闭包的$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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么我的Laravel模型关系无法保存? - Why isn't my Laravel model relationship saving? Laravel Spatie 权限 - 未找到基表或视图:1146 表“my_database.models”不存在 - Laravel Spatie Permissions - Base table or view not found: 1146 Table 'my_database.models' doesn't exist 我无法在数据库关系中访问MODEL字段 - I can't acces the MODEL field on my database relationship 为什么我在视图中看不到我的 GrandTotal? - Why Can't I See My GrandTotal In My View? Laravel Spatie 权限 - 如何通过另一个 model 更改默认 model '角色' - Laravel Spatie Permissions - how to change default model 'role' by another model Test中使用Spatie Permissions没有权限 - Using Spatie Permissions in Test doesn't have permissions Laravel spatie/laravel-permissions 的问题(HasRole 在 Model 用户中) - Problem with Laravel spatie/laravel-permissions ( HasRole in Model User ) laravel 中的权限方法和 spatie 和用户表相互冲突 - permissions method in laravel and spatie and user table conflicting with each other Spatie/Laravel-Permissions:未定义的方法 translationEnabled() 错误 - Spatie/Laravel-Permissions: Undefined method translationEnabled() error Laravel spatie/laravel-activitylog - 在 model [Spatie\Activitylog\Models\Activity] 上调用未定义的关系 [用户] - Laravel spatie/laravel-activitylog - Call to undefined relationship [user] on model [Spatie\Activitylog\Models\Activity]
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM