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

HotChocolate GraphQL如何查询包含null子对象的所有数据

GraphQL查询关联对象为空的记录解决方案

你原来的写法失效的核心原因是给accountManager传入了嵌套筛选对象,服务端会默认你需要对accountManager的内部字段做条件匹配,不会识别为判断整个关联对象为空。可以用以下两种通用方案实现需求:

方案1:使用关联对象的存在性判断运算符

主流GraphQL服务端(Prisma、Hasura、Strapi等)都针对关联字段提供了专门的空值/存在性判断语法,不需要进入嵌套字段筛选:

  • Prisma体系写法:
{
  GetAllAccounts(where: { accountManager: null }) {
    accountManagerFid
    accountManager {
      userLastName 
    }
  }
}
  • Hasura/Strapi体系写法:
{
  GetAllAccounts(where: { accountManager: { isNull: true } }) {
    accountManagerFid
    accountManager {
      userLastName 
    }
  }
}

方案2:通过外键字段筛选(兼容性最高)

你的查询返回字段中包含accountManagerFid关联外键字段,直接判断外键为null即可,只要外键为空,对应的accountManager关联对象必然不存在,这种写法几乎所有GraphQL实现都支持:

{
  GetAllAccounts(where: { accountManagerFid: { eq: null } }) {
    accountManagerFid
    accountManager {
      userLastName 
    }
  }
}

如果你的服务端有自定义的筛选规则,可优先查阅关联字段支持的运算符列表,上述两种方案可覆盖绝大多数通用场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 20:30:02