我知道这是一个老问题,但我在 laravel nova 所属领域面临同样的问题,在某些资源中,我有一个与用户相关的所属,但这些在另一个资源中应该是“主管”角色,我有一个所属领域与用户有关,但这些应该是角色“守卫”,因为 laravel nova 属于字段只需要所有用户都选择所有出现的用户,而且似乎 nova 属于字段没有办法,或者至少我没有找到它的范围查询,所以我所做的是创建一个名为 BelongstoScoped 的 php 类,这个类扩展了 laravel nova 字段 BelongsTo,所以我覆盖了负责创建查询的方法
<?php
namespace App\Nova\Customized;
use Laravel\Nova\Query\Builder;
use Laravel\Nova\Fields\BelongsTo;
use Laravel\Nova\Http\Requests\NovaRequest;
class BelongsToScoped extends BelongsTo
{
private $modelScopes = [];
//original function in laravel belongsto field
public function buildAssociatableQuery(NovaRequest $request, $withTrashed = false)
{
$model = forward_static_call(
[$resourceClass = $this->resourceClass, 'newModel']
);
$query = new Builder($resourceClass);
//here i chaned this:
/*
$query->search(
$request, $model->newQuery(), $request->search,
[], [], ''
);
*/
//To this:
/*
$query->search(
$request, $this->addScopesToQuery($model->newQuery()), $request->search,
[], [], ''
);
*/
//The method search receives a query builder as second parameter, i just passed the result of custom function
//addScopesToQuery as second parameter, thi method returns the same query but with the model scopes passed
$request->first === 'true'
? $query->whereKey($model->newQueryWithoutScopes(), $request->current)
: $query->search(
$request, $this->addScopesToQuery($model->newQuery()), $request->search,
[], [], ''
);
return $query->tap(function ($query) use ($request, $model) {
forward_static_call($this->associatableQueryCallable($request, $model), $request, $query, $this);
});
}
//this method reads the property $modelScopes and adds them to the query
private function addScopesToQuery($query){
foreach($this->modelScopes as $scope){
$query->$scope();
}
return $query;
}
// this method should be chained tho the field
//example: BelongsToScoped::make('Supervisores', 'supervisor', 'App\Nova\Users')->scopes(['supervisor', 'active'])
public function scopes(Array $modelScopes){
$this->modelScopes = $modelScopes;
return $this;
}
}
?>
在我的用户模型中,我有这样的主管和警卫角色的范围:
public function scopeActive($query)
{
return $query->where('state', 1);
}
public function scopeSupervisor($query)
{
return $query->role('supervisor');
}
public function scopeSuperadmin($query)
{
return $query->role('superadmin');
}
public function scopeGuarda($query)
{
return $query->role('guarda');
}
所以在 laravel nova 资源中我只包含了这个类的使用
*记住命名空间取决于你如何命名你的文件,在我的例子中,我创建了自定义文件夹并将文件包含在其中:
use App\Nova\Customized\BelongsToScoped;
在 nova 资源的字段中我是这样使用的:
BelongsToScoped::make('Supervisor', 'supervisorUser', 'App\Nova\Users\User')
->scopes(['supervisor', 'active'])
->searchable()
这样我就可以调用nova资源中的belongsto字段,根据模型范围过滤用户。
我希望这对某人有所帮助,如果我的英语不是那么好,请见谅。