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

如何将Hasura GraphQL查询中数组类型的stateIds参数设为可选

问题原因
  • 原查询中stateIds为空数组时,_in: []的逻辑是匹配id不存在于空数组的记录,自然无返回结果。
  • 你修改[Int!]为[Int]报错,是因为Hasura预设的_in运算符要求参数类型为元素非空的数组[Int!],你放宽了元素的非空约束导致类型不匹配,和参数是否可选无关。
解决方案

方案1:修改GraphQL查询使用动态过滤(无需改动核心业务逻辑)

保持stateIds的元素类型为Int!不变,将整个参数设为可选,配合@skip指令动态跳过过滤条件,修改后的完整查询如下:

# stateIds设为可选参数,默认值为null
query restrictionsTrav($match: String, $offset: Int, $stateIds: [Int!] = null) {
  destinations_for_travel(
    limit: 100, 
    offset: $offset, 
    where: {
      city_name: {
        name: {_ilike: $match}, 
        province_name: {
          state_Name: {
            # stateIds为null时跳过该过滤条件,不限制州id
            id: {_in: $stateIds} @skip(if: $stateIds == null)
          }
        }
      }
    }) {
    is_Travel_Allowed
    city_status {
      name
      status
    }
    city_name{
      name
      province_name{
        name
        key
        state_Name{
          name
          long_name
          key
        }
      }
    }
    updated_at
  }
}

使用时如果stateIds为空数组,只需在传参时将空数组转为null即可触发跳过逻辑,返回所有匹配match的结果。

方案2:业务代码动态组装查询条件

如果你的Hasura版本不支持在输入字段上使用@skip指令,可以在调用接口的代码中动态构造where参数,伪代码示例如下:

const where = {
  city_name: {
    name: {_ilike: match}
  }
}
// 仅当stateIds不为空时才加入州id过滤条件
if (stateIds?.length) {
  where.city_name.province_name = {
    state_Name: {
      id: {_in: stateIds}
    }
  }
}
// 发起查询时传入构造好的where参数

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 14:45:08