Sequelize Associate not found

别说谁变了你拦得住时间么 提交于 2019-12-31 07:06:05

问题


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:


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



来源:https://stackoverflow.com/questions/44938556/sequelize-associate-not-found

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!