如何在GraphQL查询中仅获取指定布尔字段值为true的奖金数据
结论
该需求完全可以直接在GraphQL查询中实现,无需做前端二次过滤,有两种成熟的优化方案,改造成本极低。
方案1:适配现有写法的最小改动(推荐保留分类型返回结果时使用)
利用GraphQL内置的@include指令即可实现需求:只有当传入的变量值为true时,才执行对应子查询,变量为false时直接跳过该子查询,不会返回对应结果。同时将子查询的where条件固定为对应字段等于true即可。
改后的查询代码如下:
import { gql } from "@apollo/client"; const BONUSES_QUERY = gql` query bonuses( $welcomeBonus: Boolean! $depositBonus: Boolean! $monthlyBonus: Boolean! $weeklyBonus: Boolean! $slotsBonus: Boolean! $noDepositBonus: Boolean! ) { welcomeBonuses: bonuses(where: { welcome_bonus: true }) @include(if: $welcomeBonus) { ...BonusParts } depositBonuses: bonuses(where: { deposit_bonus: true }) @include(if: $depositBonus) { ...BonusParts } monthlyBonuses: bonuses(where: { monthly_bonus: true }) @include(if: $monthlyBonus) { ...BonusParts } weeklyBonuses: bonuses(where: { weekly_bonus: true }) @include(if: $weeklyBonus) { ...BonusParts } slotsBonuses: bonuses(where: { slots_bonus: true }) @include(if: $slotsBonus) { ...BonusParts } noDepositBonuses: bonuses(where: { nodeposit_bonus: true }) @include(if: $noDepositBonus) { ...BonusParts } } fragment BonusParts on Bonuses { id name slug welcome_bonus deposit_bonus monthly_bonus weekly_bonus slots_bonus nodeposit_bonus } `; export default BONUSES_QUERY;
方案2:合并为单查询(推荐无需分类型返回结果时使用)
现有拆分多子查询的写法会存在重复数据问题:如果某条奖金同时符合多个类型规则,会被多次返回,后续还需要额外做去重处理。可以合并为单次查询,前端根据用户勾选的选项动态拼接OR逻辑的过滤条件,一次返回所有符合要求的无重复结果。
查询代码示例:
import { gql } from "@apollo/client"; const BONUSES_QUERY = gql` query bonuses($where: BonusesWhereInput!) { bonuses(where: $where) { ...BonusParts } } fragment BonusParts on Bonuses { id name slug welcome_bonus deposit_bonus monthly_bonus weekly_bonus slots_bonus nodeposit_bonus } `; export default BONUSES_QUERY;
前端调用查询时,根据用户勾选状态动态构造where参数即可:
// 示例:用户勾选了welcomeBonus和depositBonus const where = { OR: [ { welcome_bonus: true }, { deposit_bonus: true } ] } // 如果用户未勾选任何选项,可根据产品需求传入{}返回所有奖金,或传入无效条件返回空列表
方案对比
- 不推荐前端二次过滤:会拉取大量无用数据,浪费带宽,数据量较大时会明显拖慢页面性能。
- 方案1适配现有业务逻辑,改造成本最低,适合需要按奖金类型分别处理结果的场景。
- 方案2查询效率更高,没有重复数据,适合只需要聚合展示所有符合条件奖金的场景。
内容的提问来源于stack exchange,提问作者Cult of Tranquility
相关产品推荐
相关产品推荐

