Category
model
Thinking a little about this situation, creating a Category
model is definitely the way to go.
For example, imagine that you want users to subscribe to their favorite categories later. Or if you need a list of all existing categories? Using string lists, you will need to query all the books and somehow process all the categories received. Handling this at the model level, rather than using string lists, looks much more natural.
Instead, you can create a new Category
model and add a many-to-many relationship between Category
and Book
. In situations like this, I like to add a unique tag
enumeration field and a text
string field. (A single string tag
field in itself would also probably be a matter of taste.)
With this setting, you can easily fulfill data requirements, such as
Which books are assigned to a particular category?
query { # query books by unique category tag Category(tag: MYSTERY) { books { id } } # query books by specific category text Category(filter: { text: "mystery" }) { books { id } } }
Which books are assigned to at least one category in this list?
query { allCategories(filter: { OR: [{ tag: MYSTERY }, { tag: MAGIC }] }) { books { id } } }
What books are assigned to all categories in this list?
query { allCategories(filter: { AND: [{ tag: MYSTERY }, { tag: MAGIC }] }) { books { id } } }
Related Filters
Despite the fact that the above queries correspond to the specified data requirements, the books are grouped by Category
in the response, which means that we will have to smooth out the groups on the client.
With so-called related filters, we can turn around so that we get books only on the basis of the conditions that determine the categories associated with them.
For example, to request books assigned to at least one category in this list :
query { allBooks(filter: { OR: [{ categories_some: { tag: MYSTERY }, categories_some: { tag: MAGIC } }] }) { id } }