如何在React/Apollo中向Strapi发起带大于/小于条件的GraphQL查询
解决方案
你可以直接基于Strapi原生的GraphQL区间过滤操作符实现需求,修改如下:
- 给查询变量补全类型:原来的
$min_bonus和$max_bonus没有指定类型,需要对应你Strapi后台amount字段的类型,通常金额类字段为Float类型,若你设置的是整数类型则替换为Int即可 - 在每个分类的
bonuses查询的where条件中添加金额区间过滤规则,Strapi 使用_gte(大于等于)、_lte(小于等于)操作符实现数值区间过滤
修改后的完整查询代码如下:
import { gql } from "@apollo/client"; const BONUSES_QUERY = gql` query bonuses( $min_bonus: Float, $max_bonus: Float, $welcome_bonus: Boolean, $deposit_bonus: Boolean, $monthly_bonus: Boolean, $weekly_bonus: Boolean, $slots_bonus: Boolean, $nodeposit_bonus: Boolean ) { welcome_bonuses: bonuses(where: { welcome_bonus: $welcome_bonus, amount_gte: $min_bonus, amount_lte: $max_bonus }) { ...BonusParts } deposit_bonuses: bonuses(where: { deposit_bonus: $deposit_bonus, amount_gte: $min_bonus, amount_lte: $max_bonus }) { ...BonusParts } monthly_bonuses: bonuses(where: { monthly_bonus: $monthly_bonus, amount_gte: $min_bonus, amount_lte: $max_bonus }) { ...BonusParts } weekly_bonuses: bonuses(where: { weekly_bonus: $weekly_bonus, amount_gte: $min_bonus, amount_lte: $max_bonus }) { ...BonusParts } slots_bonuses: bonuses(where: { slots_bonus: $slots_bonus, amount_gte: $min_bonus, amount_lte: $max_bonus }) { ...BonusParts } nodeposit_bonuses: bonuses(where: { nodeposit_bonus: $nodeposit_bonus, amount_gte: $min_bonus, amount_lte: $max_bonus }) { ...BonusParts } } fragment BonusParts on Bonuses { name casino { name aff_link logo { url } } slug title amount code min_deposit value wager cashable bonus_type { name } } `; export default BONUSES_QUERY;
调用说明
你在使用useQuery发起请求时,按需传入参数即可:
- 若不需要限制最小值,给
min_bonus传null - 若不需要限制最大值,给
max_bonus传null
Strapi会自动忽略值为null的过滤条件,不会影响正常查询。
调用示例:
import { useQuery } from "@apollo/client"; import BONUSES_QUERY from "./你的查询文件路径"; // 业务代码中调用 const { data, loading, error } = useQuery(BONUSES_QUERY, { variables: { min_bonus: 50, // 最低奖金50 max_bonus: 5000, // 最高奖金5000 welcome_bonus: true, // 其他分类变量按需传入 } });
内容的提问来源于stack exchange,提问作者Cult of Tranquility
相关产品推荐
相关产品推荐

