使用 sequelize 关联不同的模型?

编程入门 行业动态 更新时间:2024-10-28 02:21:04
本文介绍了使用 sequelize 关联不同的模型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

您好,我正在尝试将我的用户模型与登录模型和 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 关联不同的模型?

本文发布于:2023-10-20 03:15:59,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1509680.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:模型   sequelize

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!