You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

API Platform自定义过滤器无法接收数组参数的配置问题排查

解决API Platform自定义过滤器无法接收数组参数的问题

1. 修正getFilterDescription的配置

API Platform需要明确的OpenAPI上下文定义才能正确识别数组类型的查询参数,仅设置type => 'array'不足以让系统正确解析。修改你的配置如下:

[
    'attributes' => [
        'property' => 'attributes',
        'type' => 'array',
        'required' => false,
        'openapi_context' => [
            'type' => 'array',
            'items' => [
                'type' => 'string', // 根据实际参数类型调整,比如int
            ],
            'style' => 'form',
            'explode' => true, // 适配前端?attributes[]=a&attributes[]=b的传参格式
        ],
    ],
];

2. 在apply方法中正确解析数组参数

即使配置正确,默认请求参数解析可能不会自动将字符串转为数组,需要手动处理:

public function apply(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, string $operationName = null)
{
    $request = $this->requestStack->getCurrentRequest();
    if (!$request) {
        return;
    }

    // 获取参数,默认返回空数组
    $attributes = $request->query->get('attributes', []);
    // 兼容前端传逗号分隔字符串的情况(如?attributes=a,b,c)
    if (is_string($attributes)) {
        $attributes = array_filter(explode(',', $attributes));
    }

    if (empty($attributes)) {
        return;
    }

    // 这里编写你的过滤逻辑,以Doctrine JSON字段查询为例
    $alias = $queryBuilder->getRootAliases()[0];
    $queryBuilder->andWhere(sprintf('JSON_CONTAINS(%s.attributes, :attributes)', $alias))
        ->setParameter('attributes', json_encode($attributes));
}

3. 确认前端传参格式

确保前端使用匹配配置的数组传参方式:

  • 方式1:?attributes[]=value1&attributes[]=value2(对应配置里的explode: true)
  • 方式2:?attributes=value1,value2(需在apply方法中做逗号分割解析)

内容的提问来源于stack exchange,提问作者Tac Tacelosky

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 19:58:04