0

I want to create 2 related objects, e.g. 1 Location and 1 Place where Place has a reference to Location like so:

type Location {
    id: String
    name: String
}

type Place {
    id: String
    locationId: String
}

Is it possible to do this with 1 mutation request? Currently I'm doing this with 2 separate mutation requests like below:

mutation ($locationName: String!) {
  insert_Location(objects: {name: $locationName}) {
    returning {
      id
    }
  }
}

//in another request, use the id returned from the request above
mutation ($locationId: String!) {
  insert_Place(objects: {locationId: $locationId}) {
    returning {
      id
    }
  }
}

I'm aware it's possible to have multiple fields in a mutation so I could create 2 Locations in 1 mutation request like below.

mutation ($locationName: String!) {
  location1: insert_Location(objects: {name: $locationName}) {
    returning {
      id
    }
  }

  location2: insert_Location(objects: {name: $locationName}) {
    returning {
      id
    }
  }
}

However if I wanted to do this to create 1 Location and 1 Place, is there a way to retrieve the created Location Id and pass it to the 2nd field to create the Place?

richflow
  • 1,902
  • 3
  • 14
  • 21
  • 1
    It sounds like these 2 data types are related, do you have foreign key relationships between these tables? Hasura lets you insert new rows on other tables inside the `objects` argument and takes care of connecting them if you have FK relationships between them – Xetera Apr 21 '20 at 05:00
  • 1
    @Xetera Yes, Place.id is a foreign key to Location.id. Ah, I just found the relevant documentation for this: https://hasura.io/docs/1.0/graphql/manual/mutations/insert.html#insert-an-object-along-with-its-related-objects-through-relationships – richflow Apr 21 '20 at 12:24

1 Answers1

0

For future reference:

As @Xetera pointed out, because the 2 types have a foreign key relationship you can do a nested insert mutation where hasura would handle setting the foreign key value. In my case it would look something like:

mutation ($locationName: String!) {
  insert_Place(
    objects: {
      Location: {data: {name: $locationName}}, //hasura will create Location and assign the id to Place.locationId
    }
  ) {
    returning {
      id
    }
  }
}

Docs here for further reading: https://hasura.io/docs/1.0/graphql/manual/mutations/insert.html#insert-an-object-along-with-its-related-objects-through-relationships

richflow
  • 1,902
  • 3
  • 14
  • 21