Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Graphql - Is there a way how to insert two tables at the same time, but the second table is dependent on the return of from the first table?

i am new to graphql and i am having this issue and don't know how to solve it.

for example i have two tables: book and book_author;

book has book_id and name book_author has book_author_id, book_id, author_name

that two tables needs to be inserted values at a single request but the book_author table needs the book_id which from the book table it self with be generated.

can someone help me with this? help is much appreciated.

expected result is when calling post request or upon inserting.

for ex. the system generated book_id bk123, the book_id in the table book_author should be the same too.

like image 907
rosiejaneenomar Avatar asked Jan 26 '23 22:01

rosiejaneenomar


1 Answers

It is possible - the important documentation is here: https://hasura.io/docs/latest/graphql/core/databases/postgres/mutations/multiple-mutations/#insert-an-object-and-a-nested-object-in-the-same-mutation

mutation {
  insert_book_author(objects: {book: {data: {name: "New Book"}}, author_name: "Sarah"}) {
    affected_rows
    returning {
      book_author_id
      book {
        book_id
        name
      }
    }
  }
}

Notice how an id is not specified in the nested book object. Hasura will automatically fill that in upon insert.

add a book table

add a book_author table, with foreign key to book

add an object relationship between book and book_author

run a mutation with nested objects

like image 188
avimoondra Avatar answered Jan 28 '23 12:01

avimoondra