在 Laravel 中的每个查询构建器调用模型之前应用过滤器
Apply filter before every query builder call for a model in Laravel
是否可以在每次要查询特定模型时应用过滤器?所以不要每次都写这样的东西:
User::where('exclude', false)->all();
User::where('exclude', false)->first();
User::where('exclude', false)->where(...);
...
您可以在模型本身中包含那个 where 子句吗?结果将使上述查询如下所示:
User::all();
User::first();
User::where(...);
...
使字段 exclude
设置为 true 的所有用户不出现在查询结果中。
此外,它是否也适用于引用模型的每个关系?例如:
$post->user();
$group->users();
不确定如何解决这个问题。首先,我尝试重写这样一个方法:
public static function all($columns = []) {
return self::where('exclude', false)->get($columns);
}
然而,它似乎没有做任何事情。此外,即使这样做,它也只会影响专门使用 all()
方法的查询调用,而不影响其他方法。
你说的是全局范围:https://laravel.com/docs/5.7/eloquent#global-scopes
看起来像这样:
class User extends Model
{
protected static function boot()
{
parent::boot();
static::addGlobalScope('exclude', function (Builder $builder) {
$builder->where('exclude', false);
});
}
}
这会影响对此模型的任何查询。如果需要,您可以即时删除它:
User::withoutGlobalScope('exclude')->get();
是否可以在每次要查询特定模型时应用过滤器?所以不要每次都写这样的东西:
User::where('exclude', false)->all();
User::where('exclude', false)->first();
User::where('exclude', false)->where(...);
...
您可以在模型本身中包含那个 where 子句吗?结果将使上述查询如下所示:
User::all();
User::first();
User::where(...);
...
使字段 exclude
设置为 true 的所有用户不出现在查询结果中。
此外,它是否也适用于引用模型的每个关系?例如:
$post->user();
$group->users();
不确定如何解决这个问题。首先,我尝试重写这样一个方法:
public static function all($columns = []) {
return self::where('exclude', false)->get($columns);
}
然而,它似乎没有做任何事情。此外,即使这样做,它也只会影响专门使用 all()
方法的查询调用,而不影响其他方法。
你说的是全局范围:https://laravel.com/docs/5.7/eloquent#global-scopes
看起来像这样:
class User extends Model
{
protected static function boot()
{
parent::boot();
static::addGlobalScope('exclude', function (Builder $builder) {
$builder->where('exclude', false);
});
}
}
这会影响对此模型的任何查询。如果需要,您可以即时删除它:
User::withoutGlobalScope('exclude')->get();