usermp / laravel-filter
用于可筛选特性的 Laravel 扩展包
dev-master
2024-07-09 11:10 UTC
Requires
- php: ^8.0|^8.1|^8.2|^8.3
- illuminate/support: *
This package is auto-updated.
Last update: 2024-09-09 11:29:38 UTC
README
概述
Filterable 特性旨在用于 Laravel 中的 Eloquent 模型。它提供了一种方便的方法,根据 HTTP 请求参数对 Eloquent 查询应用过滤器。该特性支持按模型属性以及相关模型进行筛选。
安装
- 使用 Composer 将包添加到您的项目中
composer require usermp/laravel-filter
- 将
Filterable特性添加到您的 Eloquent 模型
use Usermp\LaravelFilter\Traits\Filterable; class YourModel extends Model { use Filterable; // Define the attributes that can be filtered protected $filterable = [ 'attribute1', 'attribute2', // Add other filterable attributes ]; // Define the relationships that can be filtered protected $filterableRelations = [ 'relation1', 'relation2', // Add other filterable relations ]; }
使用方法
要使用 Filterable 特性,只需在您的模型查询上调用 filter 范围,并传递 HTTP 请求参数。
use App\Models\YourModel; $filteredResults = YourModel::filter()->get();
该特性将自动处理请求参数,将对查询应用相关过滤器,并返回筛选后的结果。
示例
单选筛选
假设您有一个 Post 模型,其中 title 和 content 是可筛选的属性,以及一个作为可筛选关系的 User 关系。
use Usermp\LaravelFilter\Traits\Filterable; class Post extends Model { use Filterable; protected $filterable = ['title', 'content']; protected $filterableRelations = ['user']; }
您可以使用以下 HTTP 请求参数按标题、内容或用户属性筛选帖子
GET /posts?title=example&user.name=john
此请求将筛选包含 "example" 标题和包含 "john" 的相关用户名的帖子。
多选筛选
假设您想按多个类别筛选帖子。 categories 属性是类别 ID 的数组。
use Usermp\LaravelFilter\Traits\Filterable; class Post extends Model { use Filterable; protected $filterable = ['title', 'content', 'categories']; protected $filterableRelations = ['user']; }
您可以使用以下 HTTP 请求参数按多个类别筛选帖子
GET /posts?categories[]=1&categories[]=2&categories[]=3
此请求将筛选属于 ID 为 1、2 和 3 的类别的帖子。
使用多选筛选相关模型
您还可以使用多选筛选相关模型。例如,按多个用户角色筛选帖子
use Usermp\LaravelFilter\Traits\Filterable; class Post extends Model { use Filterable; protected $filterable = ['title', 'content']; protected $filterableRelations = ['user']; }
按具有多个角色的用户筛选帖子
GET /posts?user.role[]=admin&user.role[]=editor
此请求将筛选由具有 "admin" 或 "editor" 角色的用户撰写的帖子。
许可
此包是开源软件,许可协议为 MIT 许可证。