Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to set many-to-many relation in graphql mutation?

I may be missing something, but can not find any information on Apollo docs about the way to set a many-to-many relation when creating a new entry.

When the relation is one-to-many it is as simple as setting the ID of the one-side of the relationship in the many-side object.

But let's pretend I am working with Books and Authors, how would I write a graphql query that creates a Book for one (or many?) Authors?

like image 857
vgrafe Avatar asked May 10 '17 12:05

vgrafe


People also ask

Can GraphQL have multiple schemas?

It's possible to run multiple PostGraphile schemas in a single Node. js server, either mounting them at different endpoints or on the same URI and use a simple middleware to switch between them.

What is __ Typename in GraphQL?

The __typename field returns the object type's name as a String (e.g., Book or Author ). GraphQL clients use an object's __typename for many purposes, such as to determine which type was returned by a field that can return multiple types (i.e., a union or interface).

Can I have multiple GraphQL endpoints?

GraphQL is all about having a single endpoint to query the data, but there are situations where it makes sense to instead have multiple endpoints, where each custom endpoint exposes a customized schema.


1 Answers

This should probably happen at the API layer on the GraphQL server (i.e. schema). For many-to-many relationships, you should have a "join" type to denote the BookAuthor many-to-many relationship, and then add an entry to that join type.

Essentially then you'll have a type called Book, another called Author, and finally one more called BookAuthor. And you can add a few mutations to be able to manage that relationship. Perhaps...

  • addToBookAuthorConnection
  • updateBookAuthorConnection
  • removeFromBookAuthorConnection

This is a conventional setup using a Relay-spec compliant API. You can read more about how to structure your API for many-to-many relationships here.

Then, you only need to call the addToBookAuthorConnection mutation from Apollo instead to be able to add to that many-to-many connection on your frontend.

Hope this helps!

like image 106
vince Avatar answered Oct 10 '22 06:10

vince