Sequelise 1:M Relationship Demystified!
Database is a very essential element of API designs especially if some data persistence is a requirement. The power of APIs is in it’s CRUD (Create, Read, Update and Delete) capabilities. It is therefore pertinent that anyone who wishes to design APIs has a good knowledge of database, database models (tables), HTTP verbs, HTTP response codes along with a sound programming skill.
In lieu of my quest to design a Recipe sharing app, I had the opportunity earlier today to further solidify my knowledge of One-to-Many database tables relationship. I said ‘solidify’ because I am not an entire novice to this concept (being a computer Science Graduate), but working on a project is the best way to actually be sure of what you know — or think you know!
The task was to make it possible for a user to store his/her recipe ideas on my API. So, I started out by designing my database models — what you may call tables if you are from a Structured Query Language (SQL) background. The first model is the User model which contains fields about the user and the second is the Recipe model that contains the information about the recipes — like name of recipe, ingredients, directions or instructions, among others.
Since it is expected that there should be a relationship between these two models, the next task was to link the two models together by defining the kind of relationships that will exist between them. It is logical to say that a recipe can only belong to one user and that a user can create many recipes — to show how great a cook he/she is. Therefore, a One-to-Many relationship will suffice here.
A 1:m relationship is fairly easy to define.
The image above shows that the relationship should be defined within the ‘classMethods’ object in the user model definition. It is also advisable that the reverse case be defined as shown below.
And that’s it!. When you run “sequelise db:migrate” in the console and view your database schema, you see the foreign key field userId defined accordingly.
The final thing to do is to create a controller that make use of these models to create a user, create a recipe record and assign it to the necessary routes.
And there we go guys!, POSTMAN confirms my API is working as expected.
My next post will be about modifying the relationships above into a Many-to-Many relationship as I intend adding more features to my wonderful, RESTful API project.
Till then, here is your Aspiring Software Developer Pen friend wishing you a happy Coding life!