Sequelize Many-to-Many Association example – Node.js & MySQL

Sequelize Many-to-Many example Overview

In systems analysis, a Many-to-Many relationship occurs between two Entities when a One-to-Many relationship between them works both ways:

  • An element of A may be linked to many elements of B.

  • A member of B may be linked to many elements of A.

For example, assume that you want to design a Tutorial Blog data models, you can think about one Tutorial has many Tags, and one Tag can point to many Tutorials.

sequelize-many-to-many-relationship-node-js-example

This type of relationship is represented in a database by a join table: Tutorial_Tag (aka a bridging, junction or linking table).

So the relationship between Tutorial entity and Tag entity is Many-to-Many. We’re gonna do it step by step:

  • First, we setup Node.js App

  • Next, configure MySQL database & Sequelize

  • Define the Sequelize Models and initialize Sequelize

  • Then we create the Controller for creating and retrieving Entities

  • Finally we run the app to check the result

Use Sequelize for Many-to-Many Association

We’re gonna define two models using Sequelize Model:

And the associations between them:

Sequelize will automatically generate Database tables as following:

sequelize-many-to-many-relationship-node-js-diagram

Use controllers for creating and retrieving data:

Then show the tutorial with tags or tag with tutorials using findByPk() and findAll():

The result will look like this:

The way that result performs depends on how we set attributes[] and through in include[]. For example, to gain the result above, we write:

You can modify them and see the changes, like this:

Sequelize Many-to-Many Implementation in Node.js

Create Node.js App

First, we create a folder:

Next, we initialize the Node.js App with a package.json file:

Then we install necessary modules: sequelize, mysql2 with the command:

The package.json file should look like this:

Let’s create Node.js project structure like following directory tree:

sequelize-many-to-many-relationship-node-js-project-structure

Configure Sequelize and MySQL database

In the app folder, we create a separate config folder with db.config.js file like this:

First five parameters are for MySQL connection. pool is optional, it will be used for Sequelize connection pool configuration:

  • max: maximum number of connection in pool

  • min: minimum number of connection in pool

  • idle: maximum time, in milliseconds, that a connection can be idle before being released

  • acquire: maximum time, in milliseconds, that pool will try to get connection before throwing error

For more details, please visit API Reference for the Sequelize constructor.

Define the Sequelize Models

In models folder, create tutorial.model.js with following code:

This Sequelize Model represents tutorials table in MySQL database. These columns will be generated automatically: id, title, description, createdAt, updatedAt.

After initializing Sequelize, we don’t need to write CRUD functions, Sequelize supports all of them:

We’re gonna use these Sequelize Model functions in our Controller.

Now continue create Tag model with name field in tag.model.js:

Initialize Sequelize

Now create index.js file to initialize Sequelize in app/models folder.

belongsToMany() provides simple way to define the Sequelize Many-to-Many relationship.

By passing "tutorial_tag" to through above, Sequelize will automatically generate a model named tutorial_tag as the through table (junction table), with two columns: tag_id and tutorial_id.

Notice that the tutorial_tag table does not have an id field.

Create the Controller

Inside app/controllers folder, we create tag.controller.js file and export these functions:

  • create

  • findAll

  • findById

  • addTutorial

First we import database object:

Create and Save new Tag

Find all Tags

Find a Tag for a given Tag id

Add a Tutorial to a Tag

Inside app/controllers/tutorial.controller.js, we also import database object as above, then export these functions:

  • create

  • findAll

  • findById

Create and Save new Tutorial

Retrieve all Tutorials

Get the Tutorial for a given tutorial id

Check the result

Open server.js and write the following code:

– First, we import our database object and controller above. – Then we call Sequelize sync() method.

In development, you may need to drop existing tables and re-sync database. Just use force: true as following code:

Now, we’re gonna test the result by putting the next lines of code inside run() function. You can run the this Sequelize Many-to-Many Node.js application with command: node server.js.

Create Tutorials

Create Tags

Add Tutorials to Tags

Show Tag (including Tutorials) by id

Show all Tags

Show Tutorial (including Tags) by id

Show all Tutorials

Check the database:

  • tutorials table:

    sequelize-many-to-many-relationship-node-js-example-table-entity-b

  • tags table:

    sequelize-many-to-many-relationship-node-js-example-table-entity-a

  • tutorial_tag table:

    sequelize-many-to-many-relationship-node-js-example-junction-table

Last updated

Was this helpful?