首页 > 解决方案 > 如何在 API Platform 和 Sylius 中实现多字段搜索?

问题描述

我正在 Sylius 中实现产品搜索1.8.5(基于 API Platform2.5.7和 Symfony 4.4.16)。

中搜索的基本变体product.translations.name(参见下面的代码)正在工作。但现在我希望能够在多个字段中进行搜索,例如 in product.translations.nameproduct.translations.descriptionproduct.translations.short_description. 问题是,添加更多标准只会使过滤更严格,因为它背后的逻辑,在 中实现ApiPlatform\Core\Bridge\Doctrine\Orm\Filter\SearchFilter,只知道AND连接器并在andWhere(...)内部使用。

当然,作为解决方法,我可以简单地SearchFilter通过自定义的 API 平台覆盖 API 平台,然后更改我想要的逻辑。但是对于这种情况,也许有更优雅/内置的解决方案?我有一种感觉,应该是,因为我想要实现的场景是一个非常常见的场景,并且几乎每个(商店)应用程序都可能需要(产品)搜索功能。

在 API Platform / Sylius 的多个属性/字段中实现(产品)搜索的正确方法是什么?


services.yaml

imports:
    - { resource: "filters.yaml" }

filters.yaml

<?xml version="1.0" ?>
...
<resources ...>
    <resource class="%sylius.model.product.class%" shortName="Product">
        <collectionOperations>
            <collectionOperation name="admin_get">
                ...
            </collectionOperation>
            <collectionOperation name="shop_get">
                <attribute name="method">GET</attribute>
                <attribute name="path">/shop/products</attribute>
                <attribute name="filters">
                    <attribute>sylius.api.product_order_filter</attribute>
                    <attribute>sylius.api.product_taxon_code_filter</attribute>
                    <attribute>sylius.api.translation_order_name_and_locale_filter</attribute>
                    <attribute>shop.product_search_filter</attribute> <-- added
                </attribute>
            </collectionOperation>
            <collectionOperation name="admin_post">
                ...
            </collectionOperation>
        </collectionOperations>
    </resource>
</resources>

filters.yaml

services:
    # Filter Services
    shop.product_search_filter:
        autowire: false
        autoconfigure: false
        public: false
        parent: 'api_platform.doctrine.orm.search_filter'
        arguments: [ { translations.name: 'partial', translations.locale: 'exact' } ]
        tags: [ name: 'api_platform.filter' ]

标签: searchfiltersymfony4api-platform.comsylius

解决方案


推荐阅读