Graphql: One-to-many delete mutation

Viewed 273

I have a simple Graphql model User with a one-to-many relation to the model Post. I want to perform a mutation which would delete the User and all subsequent related posts. How should I structure the mutation?

1 Answers

I am a beginner in graphql but this is what I came up with:

For this you need to delete the node that has a connection to another. You can traverse the graph through the mutation to find each child node (posts) related to the parent node (user) you want to delete.

I was using apollo server and neo4j and were using the same kind of query. I think you can achieve something similar with this mutation:

mutation DeleteUser($userId: ID!) {
 deleteUser(where:  {
   id: $userId
 }, delete: {
   posts: [
     {
       delete: {
         users: [
           {
             where: {
               node: {
                 id: $userId}
               }
             }
           }
         ]
       }
     }
   ]
 }) {
   nodesDeleted
   relationshipsDeleted
 }}

You just need to pass the userId variable when you execute your query with useQuery.

FYI: I think deleting to the 3rd degree, for example a "Comment" node, is more difficult tho since you would need the 2nd degree (post) node's id, I am still trying to figure this out.

Related