使用sequelize关联不同的模型?

时间:2017-08-04 08:29:17

标签: node.js express associations sequelize.js

您好我正在尝试将我的用户模型与登录模型和Question_details模型相关联。但是,如果我使用Question_details关联,那么我正在调整eagerLodingError:用户与登录没有关联,但如果我正在评论它,那么它工作正常我该如何联想呢?

但如果我正在与

联系
User Model

    module.exports = (sequelize, DataTypes) => {
        var Users = sequelize.define('users', {
            name: {
                type: DataTypes.STRING(100)
             }
            phone: {
                type: DataTypes.BIGINT,
                unique: true
            }
        }, { freezeTableName: true });

        Users.associate = function(models) {
            Users.hasOne(models.login, {
                foreignKey: 'user_id',
                as: 'loginDetails'
            });
        };

        Users.associate = function(models) {
            Users.hasMany(models.customer_query, {
                foreignKey: 'user_id',
                as: 'queryDetails'
            });
        };

        return Users;
    };

登录模型

module.exports = (sequelize, DataTypes) => {
    var Login = sequelize.define('login', {
        user_id: {
            type: DataTypes.INTEGER
        },
        user_name: {
            type: DataTypes.STRING(500),
            isEmail: true
        },
        password: {
            type: DataTypes.STRING(500)
        },
        role_id: {
            type: DataTypes.INTEGER
        }
    }, {
        underscored: true,
        freezeTableName: true
    });

    Login.associate = function(models) {
        Login.belongsTo(models.users, {
            foreignKey: 'user_id',
            onDelete: 'CASCADE'
        });
    };
    Login.associate = function(models) {
        Login.belongsTo(models.roles, {
            foreignKey: 'role_id',
            onDelete: 'CASCADE'
        });
    };
    return Login;

};

questionDetails模型

    module.exports = function(sequelize, DataTypes) {
        var questionDetails = sequelize.define('question_details', {
            query_id: {
                type: DataTypes.INTEGER
            },
            ques_type_id: {
                type: DataTypes.INTEGER
            },
            created_by: {
                type: DataTypes.INTEGER
            },
            question: {
                type: DataTypes.TEXT
            },

        }, { freezeTableName: true });

 questionDetails.associate = function(models) {
            questionDetails.belongsTo(models.users, {
                foreignKey: 'created_by',
                onDelete: 'CASCADE'
            });
        };

        return questionDetails;
    };

1 个答案:

答案 0 :(得分:2)

您只需要定义一次关联。当你第二次定义它时,你实际上会覆盖它。因此,对于User模型,您应该实际执行...

    Users.associate = function(models) {
      Users.hasOne(models.login, {
        foreignKey: 'user_id',
        as: 'loginDetails'
      });

      Users.hasMany(models.customer_query, {
        foreignKey: 'user_id',
        as: 'queryDetails'
      });
    };

对您的登录模型执行类似操作,因为您还要覆盖那里的associate函数。

祝你好运! :)