在使用grid filter大多时候通过直接对model单字段进行各种比较运算完成的。当在复杂的model查询中想要自定义 filter 行为时该怎么办呢?
下面来通过一个示例来看看如何自定义filter:
<?phpuse Encore\Admin\Layout\Content;use App\Admin\ Models \Source;class TestController { public function __construct() { } /** * grid入口 */ public function index(Content $content) { return $content->header('Test') ->body($this->grid()); } /** * grid */ private function grid() { $grid = new Grid(new Source()); //filter过滤查询 $filter->where(function ($query) { $ids = []; //$this->input 是该查询条件的输入 $sourceV = ResourceV::whereRaw("tag_name like ‘%{$this->input}%'") ->get(); foreach ($sourceV as $v) { $ids[] = $v->resource_id; } $sourceR = ResourceR::whereRaw("tag_name like ‘%{$this->input}%'") ->get(); foreach ($sourceR as $r) { $ids[] = $r->resource_id; } $query->whereRaw("source.id in ('" . implode("','", $ids) . "')"); }, 'Tag Name'); //第二个参数“Tag Name”为输入框的标签 //强制使用表的指定 索引 tp $grid->model()->eloquent()->setTable(DB::raw('source force index (tp)')); //model联表查询 $grid->model()->select(["source.*", "resourcea.*", "resourceb.*" ]) ->where(["source.type" => 1]) ->join("resourcea", "source.source_id", "=", "resourcea.id") //join条件 ->leftJoin("resourceb", "resourcea.id", "=", "resourceb.resource_id") //left join条件 ->orderBy('source.id', 'desc'); return $grid; }}
如上代码段,我们定义一个联表查询并定义了一个复杂的filter查询条件。
上述代码有两个地方需要说明的:
- model中强制使用指定的 mysql 索引
当mysql自动优化没有给model查询提供最优的查询索引时,我们需要自己指定查询要使用的索引来优化查询效率。
$grid->model()->eloquent()->setTable(DB::raw('source force index (tp)'));//source 为索引所在的表名, tp为索引名
- 获取自定义filter输入
$filter->where(function ($query) { //查询条件的逻辑在这里 //$this->input 来获取页面上该查询条件的输入文本}, 'label');