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

如何修改GraphQL查询:空$typesList时返回全部宝可梦数据

解决方案

这在GraphQL中完全可行,由于Pokeapi的GraphQL接口基于Hasura构建,我们可以利用Hasura的条件查询语法实现需求:当$typesList为空(null或空数组)时返回所有宝可梦,当列表有值时返回对应属性的宝可梦。

修改后的查询代码

query getPokemon (
  $typesList: [Int!]
)  {
  pokemon_v2_pokemon(
    where: {
      _or: [
        # 当typesList有值时,过滤出对应属性的宝可梦
        { pokemon_v2_pokemontypes: { type_id: { _in: $typesList } } },
        # 当typesList为null或空数组时,返回所有结果
        { _or: [
          { _is_null: $typesList },
          { _expr: { sql: "array_length(\"typesList\", 1) = 0" } }
        ] }
      ]
    }
  ) {
    id
    name
    pokemon_v2_pokemontypes {
      type_id
      pokemon_v2_type {
        name
      }
    }
  }
}

逻辑说明

  • 外层_or包含两个分支,满足任意一个即可返回结果:
    1. 第一个分支是你原本的过滤逻辑,当$typesList包含有效ID时,筛选出属性ID在列表内的宝可梦。
    2. 第二个分支处理空值情况:
      • _is_null: $typesList匹配参数未传入或为null的场景。
      • _expr使用SQL表达式判断数组长度为0,匹配传入空数组[]的场景。

简化方案(仅处理null参数)

如果你只需要支持参数为null时返回全部结果(不处理空数组),可以给参数设置默认值为null,此时Hasura会忽略_in: null的过滤条件,直接返回所有结果:

query getPokemon (
  $typesList: [Int!] = null
)  {
  pokemon_v2_pokemon(
    where: { 
      pokemon_v2_pokemontypes: { type_id: { _in: $typesList } }
    }
  ) {
    id
    name
    pokemon_v2_pokemontypes {
      type_id
      pokemon_v2_type {
        name
      }
    }
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 08:22:19