【问题标题】:Indexing List Type field in a GraphQL type from within a Query查询中的 GraphQL 类型中的索引列表类型字段
【发布时间】:2019-04-14 02:21:47
【问题描述】:

假设我有以下 GraphQL Schema

query {
    allAuthors: [Author]
}

type Author {
   id: ID!
   name: String!
   books: [Book]
}

type Book {
    id: ID!
    name: String!
    author: Author!
}

现在我可以成功运行以下查询来获取所有作者及其相关书籍

query {
    allAuthors {
        name,
        books { 
             name
        }
    }
}

但是,如果我只想为所有作者获取前三本书,我该怎么做呢?我们可以从查询中索引Author 类型中的books 字段吗?如果有,怎么做?

我尝试了类似的方法,但它不起作用

query {
    allAuthors {
        name,
        books[3] { 
             name
        }
    }
}

【问题讨论】:

    标签: graphql


    【解决方案1】:

    GraphQL 没有这方面的语法。

    你可以给一个字段添加一个“limit”参数,这很常见:

    type Query {
      allAuthors(limit: Int, offset: Int): [Author!]!
    }
    type Author {
      id: ID!
      name: String!
      books(limit: Int, offset: Int): [Book!]!
    }
    

    如果您将这样的参数添加到架构中,那么您想要的查询(对于所有作者,获取前三本书)可能看起来像

    {
      allAuthors {
        name
        books(limit: 3) { 
          name
        }
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2022-01-14
      • 2020-05-05
      • 2022-10-19
      • 2021-06-20
      • 2019-01-17
      • 2018-08-15
      • 2021-11-13
      • 1970-01-01
      • 2020-07-05
      相关资源
      最近更新 更多