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

如何在Swagger中为POST请求的查询参数定义嵌套数组?

正确配置查询参数中的嵌套对象数组(Swagger-PHP)

问题根源

你之前的第一种写法错误在于@SWG\Items未明确指定type="object",Swagger无法识别这是对象数组;拆分单个参数的方式交互体验差,而直接把body参数改成query会违反Swagger规范,导致解析报错。

正确配置方式

方式1:内嵌对象定义

直接在数组参数的Items里定义对象结构,明确标注type="object":

@SWG\Post(
    path="/tariff/get-by-data",
    tags={"Tariffs"},
    operationId="actionGetByData",
    summary="Find tariffs",
    @SWG\Parameter(
        name="type",
        in="query",
        type="string",
        required=true,
        description="Type of connect"
    ),
    @SWG\Parameter(
        name="find_data",
        in="query",
        type="array",
        required=true,
        description="Array of filter objects",
        @SWG\Items(
            type="object",
            @SWG\Property(property="service", type="integer", description="Client"),
            @SWG\Property(property="tariff", type="integer", description="Tariff"),
            @SWG\Property(property="connection", type="integer", description="Connection")
        ),
        collectionFormat="multi"  # 根据后端解析逻辑选择,对象数组推荐用multi
    ),
    @SWG\Response(
        response=200,
        description="Success",
        @SWG\Schema(
            @SWG\Property(property="id", type="integer", description="Id tariff")
        )
    )
)

方式2:复用Schema定义(适合复杂结构)

先单独定义对象Schema,再在数组参数中引用,结构更清晰易维护:

# 先定义对象Schema
@SWG\Definition(
    definition="FindDataItem",
    type="object",
    @SWG\Property(property="service", type="integer", description="Client"),
    @SWG\Property(property="tariff", type="integer", description="Tariff"),
    @SWG\Property(property="connection", type="integer", description="Connection")
)

# 接口配置
@SWG\Post(
    path="/tariff/get-by-data",
    tags={"Tariffs"},
    operationId="actionGetByData",
    summary="Find tariffs",
    @SWG\Parameter(
        name="type",
        in="query",
        type="string",
        required=true,
        description="Type of connect"
    ),
    @SWG\Parameter(
        name="find_data",
        in="query",
        type="array",
        required=true,
        description="Array of filter objects",
        @SWG\Items(ref="#/definitions/FindDataItem"),
        collectionFormat="multi"
    ),
    @SWG\Response(
        response=200,
        description="Success",
        @SWG\Schema(
            @SWG\Property(property="id", type="integer", description="Id tariff")
        )
    )
)

关键说明

  • collectionFormat:指定数组的编码方式,multi对应后端常用的find_data[0][service]=1&find_data[0][tariff]=2格式,需和后端解析逻辑匹配。
  • 配置完成后,Swagger UI会生成可动态添加/删除的对象输入框,解决了拆分参数导致的交互混乱问题。

内容的提问来源于stack exchange,提问作者Noeld Visard

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 08:07:42