Sequelize Many-to-Many association – NodeJS/Express, MySQL

sequelize-many-to-many-association-nodejs-express-mysql-feature-image

In the post, we got started with Sequelize One-To-Many association. Today we’re gonna create Sequelize Many-To-Many association models with NodeJS/Express, MySQL.

Related posts:
Sequelize One-To-Many association – NodeJS/Express, MySQL
Sequelize One-To-One association – NodeJS/Express, MySQL

Sequelize Many-To-Many

Note: When calling a method such as Project.belongsToMany(User, {through: 'UserProject'}), we say that the Project model is the source and the User model is the target.

We define 2 models:

Many-To-Many associations are used to connect sources with multiple targets. And the targets can also have connections to multiple sources.

A new model UserProject will be created with projectId and userId.

sequelize many-to-many nodejs-express - normal tables

through is required. Sequelize will create accessors for both Project and User instances: getUsers, setUsers, addUser, addUsers to Project, and getProjects, setProjects, addProject, and addProjects to User.

To modify the name of models in associations, we can use the alias with as option:

foreignKey is used to set source model key in the through relation.
otherKey is used to set target model key in the through relation.

sequelize many-to-many nodejs-express - tables with alias

How to persist many-to-many entities into database?

How to retrieve all entities?

With Belongs-To-Many you can query based on through relation by using through option and select specific attributes by using attributes option.

Practice

We create a NodeJs/Express project as below structure:

Setting up NodeJs/Express project

Following the guide to create a NodeJS/Express project

Install Express, Sequelize, MySQL:

-> ‘package.json’ file:

Setting up Sequelize MySQL connection

– Setup Sequelize-MySQL connection in ‘./app/config/db.config.js’ file:

Define Sequelize models

– Project model:

– User model:

Express RestAPIs
Route

Define Project’s routes in ‘./app/controller/project.route.js’ file:

Controller

Implement Project’s controller in ‘./app/controller/project.controller.js’ file:

Server.js

Run & Check results

Start Node.js server:

Initial data

Request:

-> Logs:

-> Results:

sequelize many-to-many nodejs-express - user table

sequelize many-to-many nodejs-express - project table

sequelize many-to-many nodejs-express - join table

Fetch all entities

Request:

-> Logs:

-> Result:

Sourcecode

Nodejs-Express-Sequelizejs-Many-to-Many-Mysql

By grokonez | April 26, 2018.

Last updated on September 28, 2018.



Related Posts


Got Something To Say:

Your email address will not be published. Required fields are marked *

*