【问题标题】:Apply filter before every query builder call for a model in Laravel在每个查询构建器调用 Laravel 中的模型之前应用过滤器
【发布时间】:2019-01-22 04:17:17
【问题描述】:

是否可以在每次要查询特定模型时应用过滤器?所以不要每次都写这样的东西:

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() 方法的查询调用,而不影响其他方法。

【问题讨论】:

    标签: laravel query-builder


    【解决方案1】:

    您说的是全局范围: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();
    

    【讨论】:

    • 太棒了!供将来参考 - 请注意,删除全局范围也适用于没有问题的关系:$group->users()->withoutGlobalScope('exclude');
    猜你喜欢
    • 2020-03-08
    • 2014-06-29
    • 1970-01-01
    • 2019-05-09
    • 1970-01-01
    • 1970-01-01
    • 2014-09-23
    • 2020-04-20
    • 2021-03-11
    相关资源
    最近更新 更多