正如blog所说
一个要求是必须完全有一个根查询,并且 ...
考虑架构
type Post {
id: ID!
title: String!
text: String!
category: String
author: Author!
}
type Author {
id: ID!
name: String!
thumbnail: String
posts: [Post]!
}
# The Root Query for the application
type Query {
recentPosts(count: Int, offset: Int): [Post]!
}
这是否意味着我不能像下面这样声明另一个根查询?除了根查询,还有其他查询类型吗?
# Another query
type Query {
getPost(id: Int): [Post]!
}
# Another query
type Query {
getAuthor(id: Int): [Author]!
}
答案 0 :(得分:0)
是的,在GraphQL中只有一个根查询。但是,您可以通过提供“存根”字段+解析器来在根查询上“命名空间”您的查询,如下所示。
type Booking {
_id: ID!
event: Event!
user: User!
createdAt: String!
updatedAt: String!
}
type Event {
_id: ID!
title: String!
description: String!
date: String!
}
type RootQuery {
events: [Event!]!
bookings: [Booking!]!
}
schema {
query: RootQuery
}
答案 1 :(得分:0)
在GraphQL中,有三个操作:query
,mutation
和subscription
。尽管只需要为query
提供一种类型,但每个操作都有一个与之关联的类型-其他两个是可选的。我们将这些类型称为root operation types。
我们为这样的模式指定根操作类型:
schema {
query: Query
mutation: Mutation
}
您完全可以为查询类型命名(Query
,RootQuery
,FooBar
等)。但是,如果将其命名为Query
,则可以省略上述步骤(GraphQL将简单地假设三种根操作类型将分别命名为Query
,Mutation
和Subscription
)
我们的查询类型必须为object type,因此我们使用type
关键字来定义它并为其提供至少一个字段:
type Query {
getPost(id: Int): Post!
}
type Post {
id: ID!
title: String!
text: String!
}
使用此架构,我们现在可以编写查询。我们尚未指定Mutation
或Subscription
类型,因此我们只能执行一项操作-query
:
query {
getPost(id: 5) {
id
title
}
}
正如我们所看到的,我们将Query称为 root 操作类型,因为它表示 root 或其余模式的条目。发送到服务器的每个可执行文档都必须从此根目录开始,尽管类型会根据操作(查询,变异或订阅)而有所不同。
查询是一种对象类型,这意味着我们可以向其添加其他字段:
type Query {
getPost(id: Int): Post
getAuthor(id: Int): Author
}
type Post {
id: ID!
title: String!
text: String!
}
type Author {
id: ID!
name: String!
}
现在我们可以编写一个不同的查询:
query {
getAuthor(id: 7){
id
name
}
}
甚至请求两个字段:
query {
getPost(id: 3) {
id
title
}
getAuthor(id: 11){
id
name
}
}
您不会像问题中那样两次定义Query
-您只需添加如上所示的其他字段即可。
有关其他信息,请参见the spec和official tutorial。