How to create Many to Many relationship using Sequelize ORM (Postgres) on Express.
I found it confusing setting up a Many-to-Many (n:n) relationship between two relations (or tables) using the Sequelize ORM and so after I was able to crack it, I thought it wise to create a simple guide, hence, this.
Firstly, let me describe the scenario: There are many
users and each
user can belong to many
groups or no
group at all and each
group can contain many
users or no
users at all. So, yeah, it’s a
Many-to-Many relationship between
users table and
In order to achieve this relationship, I need a
join table and I’ll call it
GroupUsers. It will be the table that describes the relationship between
groups. It will have two columns:
groupId which are foreign keys referencing both tables (users and groups), accordingly.
Ignore the other parts of the code, I only added them for the sake of it. Focus on the
Users.associate code block. In order to create our association, we need to declare it using that block of code, just the way it is. I think it’s pretty clear what it does, no need to further explain it.
Now, the only reason I had to declare this association is so that when I get a user, I also get the list of groups they belong to. This is how it looks with the association:
Behind the scenes of the above json object:
So, as you can see, associations save you a lot of code, without the associations, I would instead have to query the
Users table and then query the
GroupUsers table and then query the
Groups table in a very spaghetti-like way.
Points to take home:
- When faced with a scenario like this, create a
- Then create an association between the tables joined.
- Have fun with the
It has been a while since I wrote this article and in that time I’ve seen that it could be way more helpful if I updated the article based on the comments readers have made. Here’s what the
Groups models looks like: