Laravel管道查询集合包:Laravel Pipeline Query Collection

2023-06-01 查询 集合 管道

Laravel Pipeline Query Collection包 包含一组用于管道的 Eloquent 查询过滤器。 

https://github.com/l3aro/pipeline-query-collection

给定一个复杂的过滤器查询,代码在查询条件方面可能会有点笨拙:

$users = User::query()
    ->when($request->name ?? null, function($query, $name) {
        $query->where('name', 'like', "%$name%");
    })
    ->when($request->is_admin ?? null, function($query, $isAdmin) {
        $query->where('is_admin', $isAdmin ? 1 : 0);
    })
    ->when($request->created_at_from ?? null, function($query, $date) {
        $query->where('created_at', '>=', $date);
    })
    ->when($request->created_at_to ?? null, function($query, $date) {
        $query->where('created_at', '<=', $date);
    })
    ->get();


使用这个包可以写成如下:

use Baro\PipelineQueryCollection;
 
// users?name=Baro&is_admin=1&created_at_from=2022-06-01&created_at_to=2022-06-31
$users = Users::query()->filter([
    new PipelineQueryCollection\RelativeFilter('name'),
    new PipelineQueryCollection\BooleanFilter('is_admin'),
    new PipelineQueryCollection\DateFromFilter('created_at'),
    new PipelineQueryCollection\DateToFilter('created_at'),
])
->get();


在撰写本文时,此软件包包含以下过滤器:

Bitwise
Boolean
Date from
Date to
Exact
Relation
Relative
Scope
Sort

你可以在 GitHub 上的 l3aro/pipeline-query-collection 开始使用这个包。 

https://github.com/l3aro/pipeline-query-collection

该包的作者还写了一篇更深入的文章——构建一个性感的查询过滤器

https://baro.rezonia.com/blog/building-a-sexy-query-filter

——它引导您了解包背后的想法。


转:

https://laravel-news.com/pipeline-query-collection

相关文章