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

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

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

Sequelize One-To-Many

One-To-Many associations are connecting one source with multiple targets. But the targets are connected to only one source.

The above code will add the attribute companyId to Product. Instances of Company has accessors getProducts and setProducts.

We can use sourceKey option to associate records on different columns:

How to persist one-to-many objects to database?

How to fetch all Companies (include Products)?

With attributes option, we can select only some attributes:

And attributes can be renamed using a nested array:

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

– Create ‘./app/config/env.js’ file:

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

Define Sequelize models

– Company model:

– Product model:

Express RestAPIs
Route

Define Company’s routes in ‘./app/controller/company.route.js’ file:

Controller

Implement Company’s controller in ‘./app/controller/company.controller.js’ file:

Server.js

Run & Check results

Start Node.js server:

sequelize one to many - nodejs, express - tables

Make an initial data request:
localhost:8081/api/companies/init

sequelize one to many - nodejs, express - tables

sequelize one to many - nodejs, express - select products

Get all Companies, include Products:

localhost:8081/api/companies/all

sequelize one to many - nodejs, express - fetch all companies products

Sourcecode

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

By JavaSampleApproach | April 24, 2018.

Related Posts


4 thoughts on “Sequelize One-To-Many association – NodeJS/Express, MySQL”

  1. Should all relationships be in the connection setup?
    If I have multiple many-to-many associations, should they all be in this file ‘./app/config/db.config.js’?

    Thanks!

Got Something To Say:

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

*