Sequelize Associations (hasOne, hasMany, belongsTo, belongsToMany) - Rest API with NodeJS and MySQL

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
today I'm going to show you how to implement sqlize associations I'm gonna teach you everything about SQL s associations with examples and finally apply what we learned to our existing application which is the blogging system rest API all right so let's get started [Music] hey guys it's Corazon here and this is the part 12 of the series building a rest API with node.js and MySQL so if you are new here make sure to subscribe and stay with the channel to follow the rest of the series so far we have done so much with node.js and MySQL in our series we have implemented a card we added an image uploader and we ran migrations and seed and so much so if you are interested the links are in the description down below alright so today we're gonna learn how to create relationships between tables using sqli's associations if you've been following this course from the beginning we are building a rest API for a Blog so in our blog we have users and post categories addresses and user roles so a user can have many posts and a post can have many comments and also a post can be belongs to many categories as well and also a user can have one address so that's how the entities are connected so if you already know what relationships are in SQL databases We join tables to create relationships between tables using relationships we can get useful data from more than one table with a single query for example let me open up one of our tables so this is our post table as you can see we have ID title content image URL and user ID then the created and updated columns so so if we run a query on this table for a record we get a response like this CVS we get the exact same data as in the table pay attention to this user ID column so this is a reference to the user that this post uh was written by so we only store the user ID in this post table so displaying just this response with this user ID doesn't make any sense right because display in this user ID just this user ID won't be helpful for the user for the reader the reader wants to know the name of the user and the email and other information of the user of the author but the thing is this information like username email and other information are stored in a different table right so it is in the users table so we need to get user information for this for this query so that's what relationships are for when you are using posql we manually join Tables by writing SQL forward but when we are using an orm we don't have to manually write SQL because or employed's dedicated functions for it in our case we are using C columns as the orm and it provides these functions to create relationships and they are called associations all right so to demonstrate all the relationships all the association types and everything I have a test controller here so in this test method I am going to demonstrate all the type of relationships using the data set we have in our blog all right so after that after the demonstration I am going to practically Implement that in Nava the controllers like post controller so that our blog can continue growing with our code base all right so let's get started here um basically they are three type of relationships the first one is one to one and that can be written as one colon one so to demonstrate this I am going to take an example for um for this relationship like in this system a user can have one address oh an address can be Belongs to Only One user so that's the one-to-one relationship in nervous system a user has one address or an address belongs to only one user and the second relationship type is unto many and that can be written as one column m for this the example I'm going to get from our system is a user can have a user has many posts right it makes sense a user can have many posts written by him or we can get another example for this system because we have since we have post and comments a post can have many comments for that particular post I'm not going to use that I'm just going to use this example a user has mini post all right the third relationship type is many too many and that can be written as M column n and the example here is a post belongs to many categories make sense right a post can be belongs to many categories for example if we if someone write block if if someone writes a blog post for a programming or something that post can have stuff like node.js viewjs laravel stuff like that so a post should have a post can belong to many categories so that's the Practical aspect of it so a post belongs to many categories so these are the three examples that I am going to demonstrate in this method in this test method and after this implementing all of this relationship types I am just going to open up my post controller and let's say we have few methods let's say we have show method and I am going to apply that relationship so that our blog is the code base is growing all right so let's Define our first relationship type one to one so here I'm using the example of user has one address or an address belongs to only one user okay first I'm going to get a user record all right since this is an async method I'm just going to use this await keyword then the model name models dot model name is um use n to get a record to get a single record with the primary key there is a method in SQL is called find by PK I'm going to use that method here as well okay let me check the table and we have two users the with user ID of 19 and 20. I'm just going to hard code the user ID here this should this should give the user record for a user ID of 19. Let's test this uh by returning this user object I'm gonna open up the postman and let's call this endpoint and yes we get the user record for particular user ID which is 19. we get the exact record as in the table okay now um all right so now let's open up our user model and we need to Define our association here our relation here all right so this is how a freshly generated model looks like in SQL ice you can there are few ways to generate a model what I prefer is using the sqli CLI typing as equalize CLI then model generate and the model name and other attributes um you can refer to an older tutorial of this series to to learn about how to generate models how to generate migration and other stuff regarding uh related to SQL as we have done so much with sqlies in this series we have implemented a crutch system so far in this series so you can follow along with the series uh to learn about more stuff with SQL ice so I'm not going to repeat those at this moment right now instead I'm just going to stick to the points which is uh associations so this is how a freshly generated model looks like there is a section to Define associations okay so here uh what we are going to do is we need to Define a one-to-one relation so in sqlise there is a dedicated method for that it's called has one okay since we use the example of user has one address we can use that method to define the relation Define the association user has one address okay here I'm going to type the user model then the method has one all right then I need to Define this other model name which is address just like this so user has one address makes sense right right after that I am going to go back to the method test method and here we need to pass a second argument it is an optional argument and here in this object we can pass an object as a second argument and here there is a field called include we need to assign an array to this include key and in this array we need to pass the model that we need the association from here we need to get the address Association so I need to pass address model like this all right so Let's test this on Postman now currently we only get the user and when we hit send we get the address object as well beautiful all right so now we got the address Association for the user for the user object and we can do the other way around as well uh as we mentioned earlier a user has one address and also an address belongs to one user so just like we got address relation for the user object we can get the user relation for the particular address object as well let's do that right now I'm going to Define a new constant called address and I'm going to do the same models model name is address and I'm going to use this find by PK function here as well let me check the addresses table we have two addresses with ID of one and two I'm just going to get the first address with id1 let's test this with Postman whether we get the I address we get the address with primary key of one and here in the address model we need to Define this same Association let me open up the address model and here I'm gonna write address here address belongs to one user so I'm gonna use this belongs to method provided by sqlice then the uh model user so address belongs to user so in the test controller here as the second argument I'm going to pass our object and here I'm just going to copy this and instead of address we can use user module all right so let's test this using Postman yes you are getting the address object and the particular user relation as well fantastic all right so now you know how to implement the one to one relationship um so I'm going to just comment this out and next I'm going to implement one to many relations one to many this is also very easy um so for the one to many relationship type the example I'm using is a user has many posts so now you know I think now you know how this works you know the pattern I'm just going to copy this code snippet and I'm going to uncomment this and here instead of address I'm going to use the user object and the user model and find my p k the 19 is a ID of 19 and here in our user model we need to Define something like this user instead of hash one user has many I'm just going to copy this has menu post let me check the model name here just model name is post so user has many posts so here in our second argument which is the object we need to include post model okay user has many posts Let's test this uh on postman by returning this I'm going to open up the postman and yes we get the user object for the particular ID and all the post written by that particular user we get that as an association as a relation it's amazing right it's really easy to use this C equalizer associations all right that's all about um one-to-many relationships and you can get the user Association for post object as well we can do the we can use the same approach using our post model I'm not going to do that I assign new to do that so you can Define the belongs to relation here and get the post model and with the user Association okay so next I'm going to show you how to implement many to many relationships all right so to implement many to many relationships I am going to use the data set of a post belong to many categories a post belongs to many categories that makes sense right in a Blog there can be many blog posts with multiple categories for example if there is a post regarding programming and that post might contain the stuff like node.js UJS SQL stuff like that so there can be multiple categories for a blog post for a single blog post so uh that's the Practical aspect of it so I'm going to implement that with post and categories so let me show you the table structure as you know we have categories we have six categories and we have post table well since a post can have multiple categories we cannot just use a column to put a category ID for a for a post so that won't work and also in the categories table since a category can have multiple posts we cannot just use a column to put what are the post for this particular categories so if you have previous experience in SQL you know what's the solution here right to solve this problem we can create another table like this I have named this with post categories because this is the table that connects post table and category stable as you can see we have two columns here post ID and category ID so we can do something like this we can put post ID and the category ID again a post ID a category ID so this way we can make the connection which post belongs to which categories here as you can see post ID 1 connects with category id1 also post ID 1 connect with category ID to and also post rd2 connected category ID 2 and also host ID to connect with category ID3 so this way we can make the connection between post and categories I hope that's clear so basically we need to have three tables to implement many to many relationships all right so now we understand the table structure all right so first I'm going to get a post with the categories that it belongs to all right so just like we did earlier foreign [Music] models dot post and then the find by PK method okay um let me open up the post table and let's see since um we have only two users I mean 19 and 20 is the primary key of the existing users um there are some records with use id1 but we don't have that record for user table let me check yes we have one post with the user ID of 19 so which is 98 is the ID so let's fetch that record using the 98 primary key and let's check whether we can get the record yes we get the post record for that particular ID which is 98. okay um then to define the association let me open up the post model and here I need to define the association all right so here I need to do something like this post just like we did earlier here we need to use belongs to many method provided by sqlice belongs to many and here as the first argument I need to pass the other model that I needs the connection which is category and as the second argument I need to pass I need to pass an object with the key of true and then I need to mention what is the connecting model that the connecting model is post category I need to mention that here in this object for the true key all right so this might work this might connect the categories uh categories table and post table with the post category table you need to pass our second argument here just like we did earlier with this include then I need to pass category model all right so let's test this by calling this endpoint and we get an empty array why is that well as you checked since we use the post ID of 98 and for the first ID of 98 we don't have any categories in this table right we don't have any connecting records for our post with the primary key of 98 so what I am going to do is since I don't have data I am going to change a record here I'm just going to use the first record of post table and I'm just going to change the user ID to 19 so that record can be used in our example so here in our code let's change the ID to 1 and let me check send yes now we get the post object and the particular categories that post belongs to let me double check the table again here we are getting the first record which is the primary key of 1 and in our post categories table the connecting table for the Post ID 1 we have category id1 and category id2 so let me check the response and here for the Post ID one we have the category ID 1 and category id2 yes so we are getting the correct categories for our post beautiful all right so now what I'm going to do is I'm going to do the other way around I mean we got the post with category associations uh we can do the opposite we can get the category with post associations all right to do that I'm going to open up the category model and I'm going to just copy this and paste it right here so here category belongs to many post through post category model and here I'm just going to copy this install the post should be category and [Music] let me check the database and let me get the first category which is node.js so I'm going to hard code the IDS one [Music] and the relation is post so I need to put pause model here all right so let's return this and check whether this is working yes we get the category and the post array as well here we have one post let me check the table um for the category ID of 1 we have only one post ID which is one yeah it's accurate let me check by passing the category ID of 2 and let's test it again yes now we get three posts for our view JS category let me check the table yes for the category of 2 we have yeah three post yes it's correct so this way you can Implement many to many relationships uh using sqlice so today in this video we learn how to Implement one to one one to many and many too many relationships I hope this demonstration is clear um I use the existing data set in our blogging system so so like I promised earlier let's apply what we learned to our existing block so I'm going to open up the post controller and there is a method called show here in the show method we are getting a single blog post so here I'm going to implement um user relation and categories relation so just like we did earlier I'm going to pass the second argument which is an object for our fine by PK method and as we have in our test method I'm going to paste this right here and let's test this on our Postman and this is the endpoint for fetching a post yes we are getting two categories that this post belongs to which is not Json qjs and let's implement the user Association as well so in our post table we only have one Association here let me Define another Association post belongs to user yes post belongs to one user so here the boss controller let's Define models user Let's test this again yes we get the categories relation and also the user relation all right so that's how we can Implement associations in sqlise so we learn all the types of relations one to one one to many and many to many uh and we practically implemented all of them and finally we applied what we learned to our existing block and this way you can Implement all the relevant relationships all the relevant associations between tables um yeah for example you can Define the comments relation here in the post model as well a post can have many comments you can Define it here and then you can include it here then you can get all the comments regarding this post all right so it's really easy to use associations in sqlise once you understand the pattern it's actually effortless so today you learn how to create relationships between tables using sqlized associations all right so I hope you enjoyed the video hit the Subscribe button if you haven't already and I'll see you guys very soon in the next video foreign
Info
Channel: coder awesome
Views: 6,599
Rating: undefined out of 5
Keywords: sequelize ORM nodejs, nodejs with Sequelize, belongsToMany association sequelize, one to one relationships, many to many relationships with sequelize, one to many relationships, hasMany relationship, rest api with nodejs and mysql, nodejs and mysql rest API, Sequelize Relationships between tables, Sequelize Associations hasOne hasMany belongsTo, mysql relationships with sequelize, sequelize associations, hasOne, hasMany, belongsTo, belongsToMany
Id: sN6Bv1EWI3w
Channel Id: undefined
Length: 34min 1sec (2041 seconds)
Published: Thu Aug 31 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.