模型不与模型 Sequelize 关联

Model not associated with Model Sequelize

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

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

Error: exam_question is not associated to exam!

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" });

exam-question.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]
})

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

TL;DR

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

Exam.hasMany(ExamQuestion);

修复方法

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

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

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

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.