5

In my graphQL schema, I have a relationship between two objects. Say Humans and Cats.

Humans have many Cats and Cats have one human.

If I want to create a new Cat belonging to a human, I need to query for the human by ID and then I need to use that ID to do a mutation to create the cat.

How can I chain these together? It seems simple but can't find an appropriate example. It is also very likely that I'm thinking about this in the wrong way.

Thariq Shihipar
  • 1,072
  • 1
  • 12
  • 27

1 Answers1

-2

I don't think it makes sense to chain them. If you want to create a new cat you need a list where you select the humans you want to add the cat to. So you already have to query for the humans, before you send the mutation.

The mutation for the cat would contain the selected human ids, the process could look like this:

  1. query for humans

const getAllHumansQuery = gql`
query getAllHumans {
   getAllHumans {
      id
      name
   }
}
`;
  1. Build form with selection of humans on the client

  2. Send create new cat mutation

// server
`
input CatInput {
  name: String!
  humanIds: [ID!]
}

createCat(newCat: CatInput!) : String
`


// client

const createCatMutation = gql `
  mutation createCat($newCat: CatInput!) {
    createCat(newCat: $newCat) {
      name
    }
  }
`;
Locco0_0
  • 3,420
  • 5
  • 30
  • 42