How to create model association in Sequelize - express JS / Node JS
Tags: node, express, sequelize, mysql
Published: 2021-03-24 14:43:41

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](https://github.com/msamgan/express-app-boilerplate)

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**

```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**


```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.

**index.js**


```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;
```
Ones you are done with this you can access all you models vie models/index.js

```js
const {Post, Author} = require('../../models');
```
You can find more about hoe to use association in accessing data here

GitHub Repo for the [above code](https://github.com/msamgan/express-app-boilerplate)

Below is the link for the video tutorial for the same.

[![How to create model association in Sequelize - express JS / Node JS](http://img.youtube.com/vi/ctdMkbwHBU0/0.jpg)](http://www.youtube.com/watch?v=ctdMkbwHBU0)