您好,我正在尝试将我的用户模型与登录模型和 Question_details 模型相关联.但是如果我使用 Question_details 关联,那么我会收到 eagerLodingError :user is not associated to login 但如果我正在评论它那么它可以正常工作我怎么能关联它?
Hi I am trying to associate my User model with login model and Question_details models.But if i am using the Question_details association then i am geeting eagerLodingError :user is not associated to login but if i am commenting it then it works fine so how can i associate it ?
但如果我与
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;};
问题详情模型
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; }; 推荐答案你只需要定义一次 associate.当您第二次定义它时,您实际上是在覆盖它.因此,对于 User 模型,您实际上应该这样做...
You only have to define associate once. When you define it the second time you're actually overwriting it. So for the User model you should actually do...
Users.associate = function(models) { Users.hasOne(models.login, { foreignKey: 'user_id', as: 'loginDetails' }); Users.hasMany(models.customer_query, { foreignKey: 'user_id', as: 'queryDetails' }); };对您的登录模型执行类似操作,因为您还在那里覆盖了 associate 函数.
Do similarly for your login model as you are also overwriting the associate function there.
祝你好运!:)
更多推荐
使用 sequelize 关联不同的模型?
发布评论