studiow / laravel-filtering
此包的最新版本(v0.0.5)没有提供许可证信息。
为集合、数据库和Eloquent查询提供统一的过滤接口
v0.0.5
2019-06-06 08:08 UTC
Requires
- illuminate/database: ^5.8
- illuminate/support: ^5.8
Requires (Dev)
- orchestra/testbench: ^3.8
- phpunit/phpunit: ^8.0
README
为集合、数据库和Eloquent查询提供统一的过滤接口
安装
推荐使用 Composer 来安装此包
composer require studiow/laravel-filter
创建
使用 Filter::make 方法创建过滤接口
//From a collection \Studiow\Laravel\Filtering\Filter::make(collect([])); //From an array (or any datastructure supported by Illuminate\Support\Collection) \Studiow\Laravel\Filtering\Filter::make([])); //From an eloquent model query \Studiow\Laravel\Filtering\Filter::make(ModelName::query()); //From an eloquent model instance \Studiow\Laravel\Filtering\Filter::make($myModelInstance)); //From a Query Builder \Studiow\Laravel\Filtering\Filter::make(\DB::table('the_table_name'));
使用方法
简单过滤
$collection = collect([ ['product' => 'Desk', 'price' => 200], ['product' => 'Chair', 'price' => 100], ['product' => 'Bookcase', 'price' => 150], ['product' => 'Door', 'price' => 100], ]); $filter = \Studiow\Laravel\Filtering\Filter::make($collection); //add a filter $filtered = $filter->where('price', 100)->items(); $filtered->all(); /* [ ['product' => 'Chair', 'price' => 100], ['product' => 'Door', 'price' => 100], ] */ //add a filter with an operator $cheap = $filter->where('price', '<', 150)->items(); $cheap->all(); /* [ ['product' => 'Chair', 'price' => 100], ['product' => 'Door', 'price' => 100], ] */
组合过滤
使用 andWhere 和 orWhere 方法组合各种过滤
$cheapChairs = $filter ->where('product', '=', 'Chair') ->where('price', '<', 150) ->items(); $cheapChairs->all(); /* [ ['product' => 'Chair', 'price' => 100], ] */ $cheapOrBookcase = $filter ->where('price', '<', 150) ->orWhere('product', 'Bookcase')->items(); $cheapOrBookcase->all(); /* [ ['product' => 'Chair', 'price' => 100], ['product' => 'Door', 'price' => 100], ['product' => 'Bookcase', 'price' => 150], ] */
运算符
以下运算符被支持
- =, ==, ===
- !=, !=
- <>, <, >, <=, >=
- BETWEEN
- IN, NOT IN
- IS NULL, IS NOT NULL
- LIKE, NOT LIKE
关于(NOT)LIKE的说明
使用 % 作为通配符
$productsEndingInR = $filter ->where('product', 'LIKE', '%r') ->items(); $productsEndingInR->all(); /* [ ['product' => 'Chair', 'price' => 100], ['product' => 'Door', 'price' => 100], ] */
结果
结果通过 items() 方法作为集合返回。