DEV Community

Mohammed Samgan Khan
Mohammed Samgan Khan

Posted on • Originally published at codebysamgan.com

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

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

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

'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;
};
Enter fullscreen mode Exit fullscreen mode

Post Model

'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;
};
Enter fullscreen mode Exit fullscreen mode

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.

index.js

const Sequelize = require("sequelize");
/**
* Database Connection.
**/
const {sequelize, DataTypes} = require('../config/connection')

const Post = require("../models/post")(sequelize, DataTypes);
const Author = require("../models/author")(sequelize, DataTypes);

const models = {
    Post,
    Author
};

// Run `.associate` if it exists,
// ie create relationships in the ORM
Object.values(models)
    .filter(model => typeof model.associate === "function")
    .forEach(model => model.associate(models));

const db = {
    ...models,
    sequelize
};

module.exports = db;
Enter fullscreen mode Exit fullscreen mode

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

const {Post, Author} = require('../../models');
Enter fullscreen mode Exit fullscreen mode

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

GitHub Repo for the above code

Discussion (0)