[扩展包] Laravel-eloquent-filter 减少你对筛选条件搜索 where 的烦恼
在我们日常代码开发中,最常见的功能就是列表筛选了。通过不同的参数,返回符合条件的内容。
在网上也看到不少各种包,写法大同小异,感觉比较繁琐,于是自己写了一个。
下面分享一个扩展包。
安装
composer require james.xue/laravel-eloquent-filter
使用
TestFilter
搜索默认数据库字段
public function code($code)
{
return $this->builder->where('code', $code);
}
public function name()
{
$this->builder->where('name', 'like', "%测试%");
}
public function mobile($mobile)
{
$mobile ? $this->builder->where('mobile', $mobile) : $this->builder;
}
一对多
public function title($title)
{
return $this->builder->whereHas('goods', function($q) use ($title){
return $q->where('title', 'like', "%{$title}%");
});
}
Controller、通过 url 筛选条件默认方法可以不写,默认搜索条件为 where($column, $keywords)
// http://baby.com/api/city?code=54526481&title=菁华粉底液(片装1.5mll)
public function index(TestFilter $testfilter)
{
Test::filter($testfilter)->get();
// Or $testfilter 可以省略,默认加载 `模型 + Filter`
Test::filter()->get();
// 支持固定筛选
Test::filter($testfilter, 'name')->get();
// Or
Test::filter($testfilter, ['name'])->get();
// 支持固定筛选带参数
$mobile = "185513215";
Test::filter($testfilter, ['mobile:'.$mobile])->get();
// 支持自定义筛选方式,example:<>、like等
$mobile = "185513215";
Test::filter($testfilter, ['mobile:'.$mobile."|<>"])->get();
}
扩展包肯定还有不足之处,最后欢迎各位 PR 以带来更好的功能
GitHub:github.com/xiaoxuan6/laravel-eloqu...
本作品采用《CC 协议》,转载必须注明作者和本文链接