创建
考虑以下类型定义
type Post {
id: ID! @id
content: String!
creator: User! @relationship(type: "HAS_POST", direction: IN)
}
type User {
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 {
name: String!
movies: [Movie!]! @relationship(type: "ACTED_IN", direction: OUT)
}
type Movie {
title: String
id: ID! @id @unique
actors: [Actor!]! @relationship(type: "ACTED_IN", direction: IN)
}
由于电影 ID 是唯一的,因此您可以在Actor 变异中使用connectOrCreate 来确保电影在数据库中存在,然后再将它们连接起来。请注意,只有@unique 或@id 字段可以在where 中使用
mutation {
createActors(input: {
name: "Tom Hanks",
movies: {
connectOrCreate: {
where: { node: { id: "1234" } }
onCreate: { node: { title: "Forrest Gump" } }
}
}
}) {
info {
nodesCreated
}
}
}
这确保了 ID 为 1234 的电影存在并已连接到"Tom Hanks"。如果电影不存在,则将使用标题"Forrest Gump" 创建它。如果具有给定 ID 的电影已存在,它也将连接到"Tom Hanks",并保留其任何标题。