如何在GraphQL的多层嵌套对象中添加查询条件
给嵌套的ProductAdvantage添加查询条件的方法
要给ProductAdvantage的displayText字段加过滤条件,核心是在关联字段contentItems上添加where参数(前提是你的GraphQL后端Schema支持这个参数,大部分支持嵌套过滤的GraphQL服务比如Prisma、Hasura都提供这个能力)。具体操作如下:
- 新增查询变量:在query的变量定义里添加针对ProductAdvantage的过滤变量
- 给关联字段加过滤条件:在
contentItems字段后添加where参数,指定对ProductAdvantage的displayText过滤规则 - 保留原有逻辑:外层产品的过滤、分页逻辑保持不变
修改后的完整查询代码如下:
query ProductSearch( $displayText_contains: String = " ", $skip: Int, $first: Int, $advantageDisplayText_contains: String = "" # 新增变量 ) { product( where: {displayText_contains: $displayText_contains} skip: $skip orderBy: {displayText: ASC} first: $first ) { displayText id bag { # 在contentItems上添加where条件,过滤ProductAdvantage的displayText contentItems(where: {displayText_contains: $advantageDisplayText_contains}) { ... on ProductAdvantage { displayText htmlBody { html } productId { contentItems { ... on Product { id } } } } } } } }
补充说明
- 如果你的后端Schema里
contentItems的where参数支持更复杂的规则(比如精确匹配、范围查询等),可以根据需求替换displayText_contains为对应操作符 - 修改后返回的
contentItems列表只会包含符合$advantageDisplayText_contains条件的ProductAdvantage项,外层产品的过滤逻辑不受影响
内容的提问来源于stack exchange,提问作者amin mohammadi
相关产品推荐
相关产品推荐

