【发布时间】:2022-11-10 07:43:49
【问题描述】:
我正在使用 Laravel Filament 并为用户模型制作了一个运行良好的资源。
我在用户表中有一个 is_admin 字段,它返回 0 和 1。我需要 is_admin = 0 的用户,但现在,我得到了所有这些用户。
我可以在灯丝中添加 where 条件以仅获取必填字段。
【问题讨论】:
我正在使用 Laravel Filament 并为用户模型制作了一个运行良好的资源。
我在用户表中有一个 is_admin 字段,它返回 0 和 1。我需要 is_admin = 0 的用户,但现在,我得到了所有这些用户。
我可以在灯丝中添加 where 条件以仅获取必填字段。
【问题讨论】:
您可以在 getTablequery() 中将 ->where('role', '0') 放在 return nameModal::query() 之后。
像这样
return nameModal::query()->where('role', '0');
【讨论】:
是的你可以。您可以在相关资源类中扩展getEloquentQuery() 函数。由于您在谈论用户模型,您可以将上述函数添加到UserResource.php,如下面的代码示例所示。
public static function getEleouentQuery () {
return User::where('is_admin',0);
}
查看this了解更多信息
【讨论】:
答案有点晚了,这里有一个深入的指南。
有两种方法可以解决它
在您的资源中,覆盖以下方法:
public static function getEloquentQuery(): Builder
{
return parent::getEloquentQuery()->where('is_admin', 0);
}
Filament 使用 eloquent 接口,因此应用全局范围也可以完成这项工作。
首先,在 AppModelsScopes 中创建一个全局范围类(不是必需的路径,只是一个建议):
<?php
namespace AppModelsScopes;
use IlluminateDatabaseEloquentBuilder;
use IlluminateDatabaseEloquentModel;
use IlluminateDatabaseEloquentScope;
class AncientScope implements Scope
{
public function apply(Builder $builder, Model $model)
{
$builder->where('is_admin', 0);
}
}
然后,修改您的用户模型以应用范围:
<?php
namespace AppModels;
use AppModelsScopesAncientScope;
use IlluminateDatabaseEloquentModel;
class User extends Model
{
/**
* The "booted" method of the model.
*
* @return void
*/
protected static function booted()
{
static::addGlobalScope(new AncientScope);
}
}
【讨论】: