search - 如何在 API Platform 和 Sylius 中实现多字段搜索?
问题描述
我正在 Sylius 中实现产品搜索1.8.5
(基于 API Platform2.5.7
和 Symfony 4.4.16
)。
中搜索的基本变体product.translations.name
(参见下面的代码)正在工作。但现在我希望能够在多个字段中进行搜索,例如 in product.translations.name
、product.translations.description
和product.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' ]
解决方案
推荐阅读
- api - MS Graph SignInActivity 属性丢失?
- javascript - 如何使用递归更新局部范围的变量
- python - Python - 如何让 Selenium send_keys 在 IE11 中工作
- visual-studio-code - VSCode Snippets 自动将光标添加到语法末尾
- react-native - 如何在本机反应中映射对象数组
- html - tailwindcss flex 对齐项目和空间
- javascript - I'd like to keep unchanged value of a field but the datebase made it to ""
- javascript - 何时在 react.js 中使用构造函数
- javascript - 如何将一个.js文件中的类导入另一个
- list - 项目符号列表的自定义颜色方案/语法?可打印?