question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

sequelize express framework many to many association not working

See original GitHub issue

can some one help in the issue Model1 is not associated to Model 2 in many to many relationship

I have a Depts Model

module.exports = function (sequelize, DataTypes) { var Depts = sequelize.define(‘Depts’, { Id: { type: DataTypes.INTEGER, allowNull: false, primaryKey: true }, Name: { type: DataTypes.STRING, allowNull: false } }, { classMethods: { associate: function (models) {

                Depts.hasMany(models.Employees, {
                    foreignKey: 'DeptId'
                });
                Depts.belongsToMany(models.Students, {
                    foreignKey: 'DeptId',
                    through: models.StudentDepts,
                    unique: false
                });
            }

        },
        timestamps: false
    },
    {
        tableName: 'Depts'
    }

);
return Depts;

};

Student Models as

module.exports = function (sequelize, DataTypes) { var Students = sequelize.define(‘Students’, { Id: { type: DataTypes.INTEGER, allowNull: false, references: { model: ‘Students’, key: ‘Id’ } }, Name: { type: ‘NCHAR’, allowNull: true } }, { timestamps: false }, { tableName: ‘Students’ }, { classMethods: { associate: function (models) { Students.belongsToMany(models.Depts, { foreignKey: ‘StudentId’, through: models.StudentDepts, unique: false }); } } } ); return Students; };

Employees Models as module.exports = function (sequelize, DataTypes) { var Employees = sequelize.define(‘Employees’, { Id: { type: DataTypes.INTEGER, allowNull: false, primaryKey: true }, Name: { type: DataTypes.STRING, allowNull: false }, DeptId: { type: DataTypes.INTEGER, allowNull: false, } }, { classMethods: { associate: function (models) { Employees.belongsTo(models.Depts); } }, timestamps: false },

    {
        tableName: 'Employees'
    }
);

return Employees

};

Many to Many Relation here in StudentDepts Model as module.exports = function(sequelize, DataTypes) { var StudentDepts = sequelize.define(‘StudentDepts’, { StudentId: { type: DataTypes.INTEGER, allowNull: false, references: { model: ‘Students’, key: ‘Id’ } }, DeptId: { type: DataTypes.INTEGER, allowNull: false, references: { model: ‘Depts’, key: ‘Id’ } } }, { timestamps: false }, { tableName: ‘StudentDepts’ });

return StudentDepts;

};

Models are initialized by indesx.js which is

var fs = require(“fs”); var path = require(“path”); var Sequelize = require(“sequelize”); var config = require(‘…/db_config’);

var sequelize = new Sequelize(config.database, config.username, config.password, { host: config.host, dialect: config.dialect, dialectOptions: { instanceName: config.instanceName }, pool: { max: config.max, min: config.min, idle: config.idle }, });

var db = {};

fs.readdirSync(__dirname) .filter(function (file) { return (file.indexOf(“.”) !== 0) && (file !== “index.js”); }) .forEach(function (file) { var model = sequelize.import(path.join(__dirname, file)); db[model.name] = model; });

Object.keys(db).forEach(function (modelName) { if (“associate” in db[modelName]) { db[modelName].associate(db); } });

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

module.exports = db;

Now the issue is when I run

models.Students.findAll({ raw: true, include: models.Depts }).then(function (data) { console.log(data); });

this works fine

but when I run

models.Depts.findAll({ raw: true, include: models.Students }).then(function (data) { console.log(data); });

This throws the error of Depts is not associated to Students!

Also how to give more than one association in classMethods ?

currently I am doing

classMethods: { associate: function (models) {

                Depts.hasMany(models.Employees, {
                    foreignKey: 'DeptId'
                });
                Depts.belongsToMany(models.Students, {
                    foreignKey: 'DeptId',
                    through: models.StudentDepts,
                    unique: false
                });
            }

        },

Issue Analytics

  • State:closed
  • Created 7 years ago
  • Comments:10 (5 by maintainers)

github_iconTop GitHub Comments

1reaction
janmeiercommented, Aug 5, 2016
var Students = sequelize.define('Students', {
        Id: {
            type: DataTypes.INTEGER,
            allowNull: false,
            references: {
                model: 'Students',
                key: 'Id'
            }
        },
        Name: {
            type: 'NCHAR',
            allowNull: true
        }
    },
        { timestamps: false },
        { tableName: 'Students' },
        {
            classMethods: {
                associate: function (models) {
                    Students.belongsToMany(models.Depts,
                        { foreignKey: 'StudentId', through: models.StudentDepts, unique: false });
                }
            }
        }
    );

You are passing 4 objects to define, instead of two, putting each option into its own object - all options should be in the same object…

0reactions
vaibhavramteke787commented, Aug 5, 2016

Thanks… that worked like a charm 😃

Read more comments on GitHub >

github_iconTop Results From Across the Web

Sequelize Many-to-Many Association example - Node.js ...
First, we setup Node.js App · Next, configure MySQL database & Sequelize · Define the Sequelize Models and initialize Sequelize · Then we...
Read more >
Advanced M:N Associations | Sequelize
This shows that one Many-to-Many relationship isn't very different from two One-to-Many relationships. The tables in the database look the same. The only ......
Read more >
How to implement many to many association in sequelize
Generally I think the problems are that we are confused about what tables created, and what methods are gained by associations.
Read more >
How to use the Sequelize belongsToMany() method with code ...
The Sequelize belongsToMany() method is used to create a Many-To-Many association between two tables. Two tables that have a Many-To-Many ...
Read more >
How to create Many to Many relationship using Sequelize ...
When faced with a scenario like this, create a join table. Then create an association between the tables joined. Have fun with the...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found