achillesp / laravel-filterable
在Laravel中过滤Eloquent模型。
1.0
2017-10-31 22:46 UTC
Requires
- php: ^7.0
- illuminate/http: ^5.5
Requires (Dev)
- illuminate/database: ^5.5
- phpunit/phpunit: ^6.4
This package is auto-updated.
Last update: 2024-09-25 21:17:17 UTC
README
此Laravel包提供了一种基于请求过滤Eloquent模型的方法。
安装
在命令行中运行:
composer require achillesp/laravel-filterable
用法
要能够过滤模型,您需要使用Filterable特质。
use Achillesp\Filterable\Filterable; class Post extends Eloquent { use Filterable; }
过滤器定义在它们自己的类中,该类扩展了Achillesp\Filterable\Filters类。在这个类中,您需要提供一个包含您想要使用的过滤器名称的$filters
数组。然后您为这些过滤器中的每一个声明一个方法,该方法相应地查询模型。您可以使用相同的过滤器类为多个模型服务,或者为每个想要过滤的模型创建不同的过滤器类。
use Achillesp\Filterable\Filters; class PostFilters extends Filters { protected $filters = ['category', 'published']; protected function category(int $categoryId) { return $this->builder->where('category_id', $categoryId); } protected function published(bool $isPublished) { return $this->builder->where('is_published', $isPublished); } }
然后您可以直接从请求或通过提供一个键值对数组来过滤模型。
根据请求进行过滤,例如在一个控制器中:
public function search(Request $request) { $filters = new PostFilters($request); $posts = Post::filter($filters)->get(); return $posts; }
或根据数组进行过滤
$filters = new PostFilters(['category' => 1, 'published' => true]); $posts = Post::filter($filters)->get();
许可证
MIT许可证(MIT)。请参阅许可证文件以获取更多信息。