我正在努力理解graphql的查询和突变语法。举个例子:
type Author {
id: Int!
firstName: String
lastName: String
posts: [Post]
}
type Post {
id: Int!
title: String
author: Author
votes: Int
}
type Query {
posts: [Post]
author(id: Int!): Author
}
查询应该是什么样子才能将帖子与作者联系起来?这是关系发挥作用的地方,还是其他什么?这是我试图解决这个问题的尝试,但没有成功。
mutation createAuthor {
createAuthor(input: {
id: 123
firstName: "Bob"
lastName: "Smith"
}) {
id
firstName
lastName
}
}
query listAuthors {
listAuthors {
items {
id
firstName
lastName
}
}
}
mutation createPost {
createPost(input: {
id: 12345
title: "Title"
votes: 345
author: {
lastName: {
contains: "Bob"
}
}
}) {
id
title
votes
author {
id
firstName
lastName
}
}
}
如有任何帮助,我们将不胜感激。我的目标是查询一位作者,返回与该作者相关的所有帖子,并创建一个向作者添加帖子的帖子突变。
一个问题中有两个问题,所以我将按照问题的顺序回答。
1.返回与作者相关的所有帖子
您的架构看起来是正确的。查询看起来像:
query {
author(id: 1) {
id
posts {
id
title
}
}
}
2.创建帖子并附加到作者
在您的示例中,如果您想公开一个接口来创建Post,那么您必须在模式中公开一个突变字段
例如:
type Mutation {
createPost(input: CreatePostInput): Post
}
如果你想在创建帖子的同时,也将其附加到作者,那么你可以添加authorId
作为输入的一部分,这里我们只想将帖子附加到现有的作者:
input CreatePostInput {
title: String
authorId: ID!
votes: Int
}
当然,这只是接口定义。我们需要实际创建Post并将其链接到解析器中的Author。
突变查询看起来像:
mutation createPost {
createPost(input: {
title: "Title"
votes: 345
authorId: "authorId1"
}) {
id
title
votes
author {
id
firstName
lastName
}
}
}
希望能有所帮助!