2
votes

I have a project I'm trying to use sequelize on. It creates the database and tables fine, but it never finds the associate class method, so it never calls the associate method.

This code works fine to create the tables (using the import method) but the Object.keys(db) iterates over each model, but it never finds the associate method.

fs.readdirSync('./models')
    .filter(function (file) {
        return (file.indexOf('.') !== 0) && (file !== 'index.js') && (file.indexOf('.js') > 0) && (file.indexOf('relations.js') !== 0 );
    })


    .forEach(function (file) {
        var model = sequelize.import('../models/' + file);
        db[model.name] = model;
    });

Object.keys(db).forEach(function (modelName) {
        if (db[modelName].associate) {
            db[modelName].associate(db);
            console.log('true');
        }
        else {
            console.log('false');

        }
    }
);

Class Code Example:

module.exports = function (sequelize, DataTypes) {

let userModel = sequelize.define('user', {
    id: {
        type: DataTypes.INTEGER,
        primaryKey: true,
        autoIncrement: true
    },
    email: {
        type: DataTypes.STRING,
        validate: {
            isEmail: true
        },
        allowNull: false
    }
}, {
    classMethods: {
        associate: function (models) {
            let createdByoptions = {
                foreignKey: 'createdByUserID'
            };
            let emailOptions = {
                foreignKey: 'emailAddressID'
            };

            userModel.hasOne(models.user, createdByoptions);
            userModel.hasOne(models.email, emailOptions)

            //userModel.hasMany(models.tenant, {foreignKey: 'id'});

        },
        addUser: function (identityID) {
            userModel.create({identityUserID: identityID});
        }
    }
});


return userModel;

};

1
What version of sequelize are you on - Shivam
You would also need to to use as since you are associating user with itself - Shivam
I'm using 4.2.1. - Bryce

1 Answers

4
votes

Sequelize has changed how associations and instance methods are defined, post version >4.

So Associations earlier defined as (for version <4)

const Model = sequelize.define('Model', {
...
}, {
classMethods: {
    associate: function (model) {...}
},
instanceMethods: {
    someMethod: function () { ...}
}
});

Should now be defined as

const Model = sequelize.define('Model', {
...
});

// Class Method
Model.belongsTo(SomeOtherModel);

Check the upgrade guide and docs