Apollo(GraphQL)在查询中获取多个元素

时间:2017-06-08 12:14:25

标签: reactjs graphql apollo

我可以在GraphQL查询中获取多个元素吗?我有很多产品列表数据,我想在我的组件中获取三个产品。我有一系列需要的产品ID,我可以将其传递给查询吗?这是我对一个产品的查询:

query ProductInCartQuery($id: ID!){
  Product(id: $id) { 
   id
   name
   price
 }
}

但是我认为我不能把它放在一个函数中并且例如对三个产品执行三次。

2 个答案:

答案 0 :(得分:7)

为您拥有的每种类型提供两种查询是很常见且非常有用的:

  1. 用于获取具有id或其他唯一字段的单个节点的查询,在您的案例中Product(您已经拥有此字段)。

    < / LI>
  2. 根据不同的过滤条件获取多个节点的查询,我们将其称为allProducts

  3. 然后,您有两个选项可以在一个查询中获取多个产品。

    首先,您可以多次使用Product查询并使用GraphQL Aliases来避免响应数据中的名称冲突:

    query ProductInCartQuery($firstId: ID!, $secondId: ID!){
      firstProduct: Product(id: $firstId) { 
        id
        ... ProductInfo
      }
    
      secondProduct: Product(id: $secondId) { 
        id
        ... ProductInfo
      }
    
      fragment ProductInfo on Product {
        name
        price
      }
    } 
    

    您可以根据要查询的ID动态构建此查询字符串。但是,如果不同的ID数量是动态的,那么最好使用allProducts查询和必要的过滤器设置:

    query filteredProducts($ids: [ID!]!) {
      allProducts(filter: {
        id_in: $ids
      }) {
        ... ProductInfo
      }
    }
    
    fragment ProductInfo on Product {
      name
      price
    }
    

    你可以在我为你准备的this GraphQL Playground中自己尝试一下。可以找到更多背景信息in this article

答案 1 :(得分:0)

要将产品ID添加到查询中,您可以定义input类型。请参阅cheat sheet

因此客户端上的查询可能如下所示:

&#13;
&#13;
query ProductsInCartQuery($productIds: ProductIds!) {
  Products(productIds: $productIds) {
    id
    name
    price
  }
}
&#13;
&#13;
&#13;

在服务器上,您可以使用input类型定义架构,如下所示:

&#13;
&#13;
input ProductIds {
  ids: [ID!]
}

type Query {
  Products(productIds: ProductIds!) {
    id
    name
    price
  }
}

schema {
  query: Query
}
&#13;
&#13;
&#13;