模型与模型Sequelize无关

时间:2017-05-01 12:59:31

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

我尝试使用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]
})

如何解决此问题并获取考试对象,包括他们的问题?

1 个答案:

答案 0 :(得分:2)

TL; DR

出于一些非直观的原因,由于as属性,这似乎正在发生。要解决此问题,只需删除as属性:

Exam.hasMany(ExamQuestion);

修复方法

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

他们看起来很糟糕:骆驼和蛇的情况混在一起。

要解决这个问题,我们可以在singular模型选项(第三个参数)中轻松定义pluralExamQuestion名称:

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