javascript - 模型不与模型 Sequelize 关联

标签 javascript mysql node.js sequelize.js model-associations

我正在尝试使用 Sequelize 在表之间建立一对多关系:ExamExam_Questions

即使表已正确创建并且我可以在 PhpMyAdmin 中看到它们,我仍然在控制台中收到以下错误:

Error: exam_question is not associated to exam!

考试.js

...
const ExamQuestion = require('./exam-question');
...

const Exam = sequelizeInstance.define("exam", {
    name: { type: Sequelize.STRING },
    date: { type: Sequelize.DATE }
});

// Build the model relations
Exam.hasMany(ExamQuestion, { as: "Questions" });

考试题.js

const ExamQuestion = Sequelize.db.define("exam_question", {
    correct_answer: {
        type: Sequelize.STRING
    },
    text: {
        type: Sequelize.STRING
    }
});
module.exports = ExamQuestion;

为了解决这个错误,我试过:

ExamQuestion.belongsTo(Exam);

但这并没有改变任何东西。

查询是:

Exam.findAll({
     include: [ExamQuestion]
})

如何解决这个问题并获取包含问题的考试对象?

最佳答案

长话短说

由于一些非常非直觉的原因,这似乎是由于 as 属性而发生的。要解决此问题,只需删除 as 属性:

Exam.hasMany(ExamQuestion);

修复方法

默认情况下,移除as属性后,Sequelize会自动添加以下方法:getExam_questionsaddExam_question等。

它们看起来很糟糕: Camel 和蛇箱混在一起。

为了解决这个问题,我们可以在 ExamQuestion 模型选项(第三个参数)中轻松定义单数复数 名称:

const ExamQuestion = Sequelize.db.define("exam_question", {
    correct_answer: {
        type: Sequelize.STRING
    },
    text: {
        type: Sequelize.STRING
    }
}, {
    name: {
        singular: "question",
        plural: "questions"
    }
});

这将指示 Sequelize 创建方法,例如 getQuestionsaddQuestion 而不是 getExam_questionsaddExam_question

关于javascript - 模型不与模型 Sequelize 关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43719481/

相关文章:

mysql - 将 "ifs"嵌套在 select-where 中以进行条件动态过滤

mysql - MySQL 中条件不适用的情况

javascript - 重命名与 Sequelize 的关联

javascript - 使用 ^ 作为默认保存前缀的优点

javascript - Knob.js - 有没有一种方法可以链接拨号盘,以便它们具有总和?

php - 如何更改 Yii2 中的默认数据库表名称?

javascript - 我是否应该创建模块实例?

node.js - 连接到 socket.io azure webapp 时出现问题

javascript - 单击链接后无法渲染 react 组件

javascript - Node.js 中的变量未异步更新