本文介绍了未找到 Sequelize Associate的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个项目正在尝试使用 sequelize.它可以很好地创建数据库和表,但它永远不会找到关联类方法,因此它永远不会调用关联方法.

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.

这段代码可以很好地创建表(使用导入方法),但 Object.keys(db) 会迭代每个模型,但它永远不会找到关联方法.

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');

        }
    }
);

类代码示例:

module.exports = function (sequelize, DataTypes) {

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;

};

推荐答案

Sequelize 改变了关联和实例方法的定义方式,发布版本>4.

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

所以之前定义为(对于版本 <4)的关联

So Associations earlier defined as (for version <4)

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

现在应该定义为

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

// Class Method
Model.belongsTo(SomeOtherModel);

查看升级指南docs

这篇关于未找到 Sequelize Associate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 02:11