How to create Many to Many relationship using Sequelize ORM (Postgres) on Express.

Michael Ozoemena

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 groups table.

My take

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 users and groups. It will have two columns: userId and groupId which are foreign keys referencing both tables (users and groups), accordingly.

The code

Users Model

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:

Users Controller

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 join table.
  • Then create an association between the tables joined.
  • Have fun with the include options.

[UPDATE]

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 GroupUsers and Groups models looks like:

GroupUsers Model

Group Model

Michael Ozoemena

Written by

Software Engineer. @the_ozmic on Twitter.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade