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

Azure静态Web应用中GraphQL的in运算符无法使用,如何实现多值过滤?

问题

我正在使用Azure Static Web App搭配Azure SQL数据库。在过滤数据时,我希望使用in运算符替代eq运算符。目前eq运算符可以正常工作,代码示例如下:

async function filterProducts() {
  const query = `
    query Products {
      products(filter: { category: { eq: "dairy" } }) {
        items {
          date
          category
          price
        }
      }
    }`;
  
  const filteredProducts = await fetch('/data-api/graphql', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ query: query })
  })
    .then((response) => response.json())
    .then((dataJson) => {
      const dataItems = dataJson.data.products.items;
      const dates = dataItems.map((product) => product.date);
      const prices = dataItems.map((product) => product.price);
      return { dates, prices };
    })
    .catch((err) => console.warn('Unable to fetch from the endpoint.', err));

  return filteredProducts;
}

然而,使用in运算符会返回400(Bad Request)错误,对应的查询代码如下:

const query = `
  query Products {
    products(filter: { category: { in: ["dairy", "fruit"] } }) {
      items {
        date
        category
        price
      }
    }
  }`;

调用localhost:4280/data-api/graphql端点时出现以下错误:

Failed to load resource: the server responded with a status of 400 (Bad Request)

请问是否可以在Azure Static Web App中使用in运算符?如何在Azure Static Web App中通过GraphQL实现多值过滤?


解答

Azure Static Web Apps搭配Azure SQL的GraphQL数据API支持in运算符,出现400错误通常是查询语法问题或模型配置未启用对应过滤能力,以下是具体解决方法:

1. 确认模型过滤配置

如果是自动生成的数据模型,字符串类型字段默认支持in过滤;如果是自定义模型,需确保category字段的过滤规则中包含in运算符。检查data-api文件夹下的模型定义文件,确保字段配置正确。

2. 修正in运算符的查询语法

在JavaScript模板字符串中,无需转义双引号,直接使用数组写法即可:

const query = `
  query Products {
    products(filter: { category: { in: ["dairy", "fruit"] } }) {
      items {
        date
        category
        price
      }
    }
  }`;

3. 替代方案:使用or运算符组合多条件

如果in仍有问题,可通过or运算符组合多个eq条件实现多值过滤,这是GraphQL标准兼容写法:

const query = `
  query Products {
    products(filter: { 
      or: [
        { category: { eq: "dairy" } },
        { category: { eq: "fruit" } }
      ]
    }) {
      items {
        date
        category
        price
      }
    }
  }`;

4. 调试错误详情

修改fetch的错误处理逻辑,打印完整响应内容,定位具体错误原因:

.catch((err) => {
  console.warn('请求失败:', err);
  if (err.response) {
    err.response.text().then(text => console.log('错误详情:', text));
  }
});

内容的提问来源于stack exchange,提问作者Péter Szilvási

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 16:05:09