diar / laravel-query-filter
查询过滤器构建包
dev-master
2022-01-25 11:40 UTC
Requires
- php: ^7.4|^8.0
This package is auto-updated.
Last update: 2024-09-25 17:43:48 UTC
README
Laravel 查询过滤器是一个包,它让创建过滤器变得简单易行。
安装
composer require diar/laravel-query-filter
用法
Book::filter()->get();
为了使用过滤器,您必须通过该包提供的命令创建一个新的过滤器
php artisan make:filter BookFilters
此命令将在内部创建一个名为 Filters 的目录和一个名为 BookFilters 的类。要使用 Book 模型的过滤器方法,请使用 Filterable 特性
<?php namespace App\Models; use Deviar\LaravelQueryFilter\Filters\Filterable; class Book extends Model { use Filterable;
并通过添加以下代码来设置模型的 defaultFilter
protected $defaultFilter = BooksFilters::class;
如果您想覆盖默认过滤器,只需在调用过滤器方法时调用 CustomFilter
Book::filter(CustomerFilter::class)->get();
包在 Filter 类中提供了许多选项
要像 /books?title=hero&author_id=2 一样在过滤器中使用属性,您必须添加
protected array $allowedFilters = ['title' , 'author_id'];
要设置包含在搜索中的列 /books?search=annabel,您必须添加
protected array $columnSearch= ['title','descriptions'];
要按关系列搜索 /books?search=kathlen,您必须添加
protected array $relationSearch = [ 'author' => ['first_name', 'last_name'] ];
要允许加载关系模型 /books?include=author,您必须添加
protected array $allowedIncludes = ['author'];
要按属性对资源进行排序,您必须添加
protected array $allowedSorts= ['created_at']; // desc : /books?sorts=created_at // asc : /books?sorts=-created_at
您可以通过在 Filter 类中创建一个新的函数来创建自定义查询,例如,通过出版日期过滤书籍
public function publish_at($date) { $this->builder->whereDate('publish_at', $date); } // /books?publish_at=20151124
或通过关系过滤
public function custom($term) { $this->builder->whereHas('options', function($query) => $query->where('custom_id', $term)); } // /books?custom=33
