#express js #node #node js #sequelize #mysql

How to create model association in Sequelize - express JS / Node JS

Table Of Content


  1. Preface
  2. Author Model (models/author.js)
  3. Post Model (models/post.js)
  4. models/index.js
  5. Accessing Models

In the very initial days of my work in Node JS if faced this issue. Though Sequelize provide a great ORM for MySQL but the association within the models is a bit tricky. you can find more about associations here

Before getting any further, if you want to get a setup for fully function code setup here it is

Preface

For the sake of understanding, lets consider two Models please inside the model directory, models/author.js and models/post.js. Models will look like as follows respectively.

Author Model (models/author.js)

'use strict';
const {
  Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
  class Author extends Model {
    /**
     * Helper method for defining associations.
     * This method is not a part of Sequelize lifecycle.
     * The `models/index` file will call this method automatically.
     */
    static associate(models) {
      // define association here
    }
  };

  Author.init({
    slug: DataTypes.STRING,
    name: DataTypes.STRING,
  }, {
    sequelize,
    modelName: 'Author',
    tableName: 'authors',
  });


  return Author;
};

Post Model (models/post.js)

'use strict';
const {
    Model,
} = require('sequelize');

module.exports = (sequelize, DataTypes) => {
    class Post extends Model {
        /**
         * Helper method for defining associations.
         * This method is not a part of Sequelize lifecycle.
         * The `models/index` file will call this method automatically.
         */
        static associate(models) {
            this.belongsTo(models.Author, {as: 'Author'});
        }
    }


    Post.init({
        slug: DataTypes.STRING,
        title: DataTypes.STRING,
        excerpt: DataTypes.STRING
    }, {
        sequelize,
        modelName: 'Post',
        tableName: 'posts',
    });

    return Post;
};

As shown in the post model, a belongs too association is made between Post and author. But as the comment suggest, associate method is not a part of Sequelize lifecycle. we have to call it manually.

To achieve that, we need to create models/index.js with the following content.

models/index.js

'use strict';

const fs = require('fs');
const path = require('path');
const Sequelize = require('sequelize');
const basename = path.basename(__filename);
const env = process.env.NODE_ENV || 'development';
const config = require(__dirname + '/../config/database.json')[env];
const db = {};

let sequelize;
if (config.use_env_variable) {
  sequelize = new Sequelize(process.env[config.use_env_variable], config);
} else {
  sequelize = new Sequelize(config.database, config.username, config.password, config);
}

fs
  .readdirSync(__dirname)
  .filter(file => {
    return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
  })
  .forEach(file => {
    const model = require(path.join(__dirname, file))(sequelize, Sequelize.DataTypes);
    db[model.name] = model;
  });

Object.keys(db).forEach(modelName => {
  if (db[modelName].associate) {
    db[modelName].associate(db);
  }
});

db.sequelize = sequelize;
db.Sequelize = Sequelize;

module.exports = db;

Ones you are done with this you can access all you models vie models/index.js

Accessing Models

const {Post, Author} = require('../../models');

You can find more about hoe to use association in accessing data here

GitHub Repo for the above code


Most Viewed Posts


Must Read


January 28, 2022

#AppImage #linux

How to Add AppImage Application to Menu in Ubuntu (Linux)

AppImages are the most easiest to run compared.The challenging task is to make the AppImage accessible globally through he system like an installed application (in the menu)

Reading time: less than a minute
How to Add Laravel Pint to VS Code Formatter
June 24, 2022

#code-quality #vscode #laravel-pint #laravel

How to Add Laravel Pint to VS Code Formatter

I have been using the unsatisfactory formatters from a long time. All of them have one thing but lack other. Laravel Pint is one who has it all, combining it with vscode is like proving you laravel project a super power.

Reading time: 2 minutes
December 14, 2021

#database #javascript #sequelize #npx

Sequelize CLI Commands

list of Sequelize CLI commands which comes handy, while working on a project.

Reading time: 1 minute
How to create a progressive web app (PWA) in laravel 5.* and above
July 07, 2019

#functionality #pwa #javascript #laravel

How to create a progressive web app (PWA) in laravel 5.* and above

The progressive web app is the new trend as well as the need for the present time. I hope before getting in the “HOW” part you know what is exactly a PWA

Reading time: 4 minutes
November 02, 2021

#laravel #tricks #eloquent

Approach to Handle Complex queries in laravel

I am familiar with the love of Eloquent among the laravel community but sometimes, sometimes its better to go for raw queries. Its saves you a lot of time and trouble.

Reading time: 1 minute
December 14, 2021

#database #javascript #sequelize #npx

Sequelize CLI Commands

list of Sequelize CLI commands which comes handy, while working on a project.

Reading time: 1 minute
February 13, 2021

#express js #node #node js #post #forms

How to get form data in post request in Express JS - Node JS

if you are starting new with Node JS, you will probably face this problem, while submitting the form to a post URL.

Reading time: less than a minute
create-express-boilerplate to create new API projects in a secs
October 25, 2021

#express js #npm #deployment #api #node #node js #javascript #npx #boilerplate

create-express-boilerplate to create new API projects in a secs

Initiating a new project is as exciting as frustrating. Going through all the routine work just to get the basic engine started, yaa I know the pain.

Reading time: less than a minute
June 20, 2022

#express js #file-upload #node js #multer

File upload in Node JS Using Multer

File upload in node js is one hell of a job. Not knowing how is makes it a bit more troublesome

Reading time: 1 minute
August 15, 2019

#cli #mysql

How to take MySQL DB back up from the command line

As you know regular backups of DB for a running site are very important. Most of the hosting providers do this for you, but sometimes its also expected from you to do the same.

Reading time: less than a minute
mohammed-samgan-khan

Hi, I am Samgan, I know the adds are bit annoying but i hope you understand. Talking about me, I excel at solving complex problems involving logic and step by step breakdown of the problem. Besides, to develop complex algorithms, I specialize in problem framing, systems design, and product development strategy. Sometimes I also enjoy public speaking.