编程

[Laravel 扩展包]Eloquent Filtering 包:在 Eloquent 中构建动态查询过滤器

400 2024-10-07 15:45:00

Eloquent Filtering 包增强了在 Eloquent 中构建动态查询过滤器的过程。无论你是管理大型数据集还是构建复杂的搜索功能,Eloquent Filtering 都有助于简化体验。

Eloquent Filtering 是什么?

Eloquent Filtering 的核心是允许开发人员根据传入的请求数据动态过滤模型。该包抽象了流程,而不是手动链接多个查询条件,从而使代码库更具可读性和可维护性。

基础示例

class Product extends Model implements IsFilterable
{
    use Filterable;
 
    public function allowedFilters(): AllowedFilterList
    {
        return Filter::only(
            Filter::field('name', [FilterType::EQUAL]),
        );
    }
}
 
$products = Product::filter([
    [
        'target' => 'name',
        'type'   => '$eq',
        'value'  => 'TV'
    ]
])->get();

字段和关联过滤器示例

class Product extends Model implements IsFilterable
{
    use Filterable;
 
    public function allowedFilters(): AllowedFilterList
    {
        return Filter::only(
            Filter::field('name', [FilterType::EQUAL]),
            Filter::relation('manufacturer', [FilterType::HAS])->includeRelationFields()
        );
    }
 
    public function manufacturer(): HasOne
    {
        return $this->hasOne(Manufacturer::class);
    }
}
 
class Manufacturer extends Model implements IsFilterable
{
    use Filterable;
 
    public function allowedFilters(): AllowedFilterList
    {
        return Filter::only(
            Filter::field('name', [FilterType::EQUAL])
        );
    }
}
 
$filters = [
    [
        'target' => 'name',
        'type'   => '$eq',
        'value'  => 'TV',
    ],
    [
        'type'   => '$has',
        'target' => 'manufacturer',
        'value'  => [
            [
                'type'   => '$eq',
                'target' => 'name',
                'value'  => 'Sony',
            ]
        ]
    ]
];
 
$sql = Product::filter($filters)->toRawSql();
SELECT *
FROM "products"
WHERE "products"."name" = 'TV'
  AND EXISTS (
    SELECT *
    FROM "manufacturers"
    WHERE "products"."manufacturer_id" = "manufacturers"."id"
      AND "manufacturers"."name" = 'Sony'
  )

官方文档:https://docs.eloquentfiltering.com/v2/introduction/eloquent-filtering