创建
这是 GraphQL 库版本 6 的文档。对于长期支持 (LTS) 版本 5,请参考 GraphQL 库版本 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。
您可以通过使用 |
connectOrCreate
关系
如果相关节点定义了 @unique
指令,则可以在 create
突变中使用嵌套的 connectOrCreate
来执行类似于对相关节点进行 Cypher MERGE
操作的操作。如果相关节点尚不存在,这将创建一个新关系和相关节点。
考虑以下类型定义
type Actor @node {
name: String!
movies: [Movie!]! @relationship(type: "ACTED_IN", direction: OUT)
}
type Movie @node {
title: String
id: ID! @id @unique
actors: [Actor!]! @relationship(type: "ACTED_IN", direction: IN)
}
由于电影 ID 是唯一的,因此可以在 Actor
突变中使用 connectOrCreate
来确保电影在连接之前存在于数据库中。请注意,只能在 where
中使用 @unique
或 @id
字段
mutation {
createActors(input: {
name: "Tom Hanks",
movies: {
connectOrCreate: {
where: { node: { id_EQ: "1234" } }
onCreate: { node: { title: "Forrest Gump" } }
}
}
}) {
info {
nodesCreated
}
}
}
这将确保存在 ID 为 1234 的电影,并将其连接到 "Tom Hanks"
。如果电影不存在,则将使用标题 "Forrest Gump"
创建它。如果具有给定 ID 的电影已经存在,它也将连接到 "Tom Hanks"
,并保留其拥有的任何标题。