查询中的GraphQL类型的“索引列表类型”字段

时间:2018-11-10 22:12:27

标签: graphql

说我有以下GraphQL模式

query {
    allAuthors: [Author]
}

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

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

现在,我可以成功运行以下查询,以获取所有作者及其关联的书

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

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

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

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

1 个答案:

答案 0 :(得分:2)

GraphQL对此没有语法。

您可以向字段添加“限制”参数,这很常见:

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
    }
  }
}