Create
Using the following type definitions for these examples:
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)
}
The following create Mutations and response types will be generated for the above type definitions:
type CreatePostsMutationResponse {
posts: [Post!]!
}
type CreateUsersMutationResponse {
users: [User!]!
}
type Mutation {
createPosts(input: [PostCreateInput!]!): CreatePostsMutationResponse!
createUsers(input: [UsersCreateInput!]!): CreateUsersMutationResponse!
}
The CreateInput
types closely mirror the object type definitions, allowing you to create not only the type in question, but to recurse down and perform further operations on related types in the same Mutation.
The
id
field will be absent from both create input types as the@id
directive has been used.
Single create
A single user can be created by executing the following GraphQL statement:
mutation {
createUsers(input: [
{
name: "John Doe"
}
]) {
users {
id
name
}
}
}
This will create a User with name "John Doe", and that name plus the autogenerated ID will be returned.
Nested create
A User and an initial Post can be created by executing the following:
mutation {
createUsers(input: [
{
name: "John Doe"
posts: {
create: [
{
node: {
content: "Hi, my name is John!"
}
}
]
}
}
]) {
users {
id
name
posts {
id
content
}
}
}
}
This will create a User with name "John Doe", an introductory Post, both of which will be returned with their autogenerated IDs.
connectOrCreate
relationships
If a related node has a @unique
or @id
directive defined, connectOrCreate
can be used in a nested create to perform a MERGE
operation on the related node, creating a new relationship and the related node if it doesn’t exist.
Consider the following type definitions:
type Actor {
name: String!
movies: [Movie!]! @relationship(type: "ACTED_IN", direction: OUT)
}
type Movie {
title: String
id: ID! @id
actors: [Actor!]! @relationship(type: "ACTED_IN", direction: IN)
}
Because a movie ID is unique, connectOrCreate
can be used in an Actor mutation to ensure a movie exists before connecting. Note that only @unique
or @id
fields can be used in where
:
mutation {
createActors(input: {
name: "Tom Hanks",
movies: {
connectOrCreate: {
where: { node: { id: "1234" } }
onCreate: { node: { title: "Forrest Gump" } }
}
}
}) {
info {
nodesCreated
}
}
}
This will ensure that a movie with ID 1234 exists and it is connected to "Tom Hanks"
. If the movie does not exist, it will be created with the title "Forrest Gump"
. Note that if the movie with the given ID already exists, it will be connected to it, regardless of the title.
Was this page helpful?