create
|
这是 GraphQL Library 7 版本的文档。对于长期支持 (LTS) 版本 5,请参考 GraphQL Library 5 LTS 版本。 |
考虑以下类型定义
type Post @node {
id: ID! @id
content: String!
creator: User! @relationship(type: "HAS_POST", direction: IN)
}
type User @node {
id: ID! @id
name: String
posts: [Post!]! @relationship(type: "HAS_POST", direction: OUT)
}
以下生成了 create 变更和响应类型
type CreatePostsMutationResponse {
posts: [Post!]!
}
type CreateUsersMutationResponse {
users: [User!]!
}
type Mutation {
createPosts(input: [PostCreateInput!]!): CreatePostsMutationResponse!
createUsers(input: [UsersCreateInput!]!): CreateUsersMutationResponse!
}
请注意,CreateInput 类型与对象类型定义高度相似。这使得您不仅可以创建所需的类型,还可以向下递归,在同一次变更中对相关类型执行进一步操作。
|
|
单个 create
通过执行以下 GraphQL 语句,可以创建单个 User。
mutation {
createUsers(input: [
{
name: "John Doe"
}
]) {
users {
id
name
}
}
}
这将创建一个名称为 “John Doe” 的 User。返回该名称及自动生成的 ID。
嵌套 create
通过执行以下语句,您可以一次性创建一个 User 及其初始的 Post。
mutation {
createUsers(input: [
{
name: "John Doe"
posts: {
create: [
{
node: {
content: "Hi, my name is John!"
}
}
]
}
}
]) {
users {
id
name
posts {
id
content
}
}
}
}
这将创建一个名称为 “John Doe” 的 User 和一篇介绍性帖子。两者都会返回其自动生成的 ID。
欲了解更多关系操作示例,请参阅 关系操作。