【问题标题】:Custom filtering on Eloquent modelEloquent 模型上的自定义过滤
【发布时间】:2019-04-07 09:58:42
【问题描述】:

我的应用程序支持使用过滤器获取数据。我目前的实现(效果很好)是

Model::select($fields)->with($relations)->tap(function ($query) use ($filters) {
  // A lot of filtering logic here
  // $query->where()...... 
})->get();

但是,我想将过滤逻辑直接移动到模型中,这样我就可以这样做了

Model::select($fields)
  ->with($relations)
  ->applyFilters($filters)
  ->get();

我尝试将filter 方法添加到Model,但此时我正在使用Builder,但它无法识别我的功能:

调用未定义的方法 Illuminate\Database\Eloquent\Builder::applyFilters()

除了创建一个新的构建器类并使用它之外,还有更简单的方法吗?

【问题讨论】:

    标签: php laravel eloquent laravel-query-builder


    【解决方案1】:

    我想通了!我只需要在我的Model 类中添加一个scopeApplyFilters。它会自动注入Builder 作为第一个参数,所以逻辑最终看起来像

    public function scopeApplyFilters($query, $filters)
    {
        // Perform filtering logic with $query->where(...);
    
        return $query;
    }
    

    那我可以直接用Model::applyFilters($filters);调用它

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-18
      • 2017-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多