Add Book and Genre associations
Now that we have genre
and author
in their own tables we want to be able to associate those two tables via a foreign key.
This is made easy by Sequelize, as using its associations hasOne
, hasMany
, belongsTo
and belongsToMany
infers foreign key relationships between tables.
Using genre
as a starting point, the Genre model should look like this (notice that there is no reference to books in the model!):
1 - We should remove any reference to genre
in the Book model, so it should now look like similar to:
2 - We will make our associations in our Sequelize setup file in /src/models/index.js
by adding the following code immediately after where we define the constants Reader
, Book
and Genre
:
3 - After setting the relationships above, Sequelize will automatically create the foreign key for GenreId
in the Books table, so you don't need to do it yourself. Therefore Book will have a new column named GenreId
(notice the capitalisation). This means if we have a row
on genres
with the value
We could create a new book with the following JSON:
More on associations in the (very good) Sequelize documentation.
4 - Query using Sequelize associations. Let's imagine that upon the creation of our book above we got back an id
of 10
. If we query our database with /books/10
we'll see that there's no mention to genre besides a GenreId
integer which, for a human, does not give us much information.
In order to get the genre beyond an id
we will need to make sure that our query for Book includes the model Genre. If you change the code of getItemById
in /src/controllers/helpers.js
so that it looks like this:
and try the endpoint again, what do you see?
It should return something similar to:
5 - This is all very good, but what about querying a genre so that it shows us all the books listed under it, which is what our requirements asked of us? At the moment if we hit the /genres
endpoint it would only shows us a list of genres with no books details.
For that we will need to add a new getAllBooks
function in /src/controllers/helpers.js
so that it includes our Book model, like so:
Try the endpoint again. We should see something to: