【问题标题】:How to filter a GraphQL query content using a specific value inside the content?如何使用内容中的特定值过滤 GraphQL 查询内容?
【发布时间】:2021-04-17 02:47:50
【问题描述】:

如何使用内容数据中的特定值过滤 GraphQL 查询内容。例如,我收到了以下 GraphQL 查询的结果。

query MyQuery {
  allPages {
    edges {
      node {
        content
      }
    }
  }
}

从上面的查询中,我收到了如下内容。我正在尝试使用“类型”值(蔬菜/水果)过滤掉结果。如何过滤掉蔬菜内容以仅显示水果内容。

{
  "node": {
    "content": [
      {
        "type": "Fruit",
        "value": {
          "Text": "Orange"
        }
      },
      {
        "type": "Fruit",
        "value": {
          "Text": "Apple"
        }
      }
    ]
  }
},
{
  "node": {
    "content": [
      { 
        "type": "Veg",
        "value": {
          "Text": "Broccoli"
        }
      },
      {
        "type": "Veg",
        "value": {
          "Text": "Lettuce"
        }
      }
    ]
  }
}

【问题讨论】:

    标签: graphql gatsby


    【解决方案1】:

    使用GraphQL filters:

    query MyQuery(filter: { content: { type: { eq: "Fruit" } } }) {
      allPages {
        edges {
          node {
            content
          }
        }
      }
    }
    

    注意:根据您的问题,我假设type 是content 中的一个属性。如果没有,请根据您的需要进行调整。使用 localhost:8000/___graphql 可以帮助您在过滤器中创建正确的 GraphQL 查询。

    如果你想为你拥有的每种数据创建不同的查询,你可以给它们起别名:

    query MyQuery {
      fruit: allPages (filter: { content: { type: { eq: "Fruit" } } }) {
        edges {
          node {
            content
          }
        }
      }
      vegetables: allPages (filter: { content: { type: { eq: "Veg" } } }) {
        edges {
          node {
            content
          }
        }
      }
    }
    

    在这种情况下,您的数据将位于 props.data.fruit 或 props.data.vegetables 内。

    【讨论】:

    • 我将测试这种方法并将状态发布在这里..谢谢@Ferran
    猜你喜欢
    • 2020-06-29
    • 2020-12-03
    • 1970-01-01
    • 2020-05-01
    • 2021-07-15
    • 2011-01-26
    • 2012-07-11
    • 1970-01-01
    • 2019-01-03
    相关资源
    最近更新 更多