graphback
graphback copied to clipboard
How to define a ManyToMany relation with parameters (i.o.w a crosstable)
Lets say we have books and we have libraries, each book can be in multiple libraries and each library can have multiple books. Also we want to keep track of how much books a library has.
Traditionally this results in a database structure like this:
Now I have been struggeling with how to define this in my graphql schema and annotate this correctly for graphback, i was convinced i needed an @manyToOne annotation, while most of graphback is @oneToMany oriented. (this took a bit to get used to and might be handy to explain a bit at the start of the documentation to reduce confusion)
Using 3 tables and @manyToOne relations got me into problems.
It turned out this many-to-many relation could be achieved by using 3 tables and inverting the relations to use a @oneToMany like so:
""" @model """
type Library {
id: ID!
name: String!
"""
@oneToMany field: 'library'
"""
libraryBooks: [LibraryBooks]
}
""" @model """
type LibraryBooks {
id: ID!
numberOfBooks: Int!
}
""" @model """
type Book {
id: ID!
name: String!
"""
@oneToMany field: 'book'
"""
libraryBooks: [LibraryBooks]
}
Although we generate @manyToOne
fields/annotations from @oneToMany
annotations, we don't support the inverse (yet).
This is why ManyToOne is not documented as an option in https://graphback.dev/docs/intro/datamodel#relationships - though I can see how this might be confusing.