我尝试使用Sequelize来表达表格之间的一对多关系:Exam
和Exam_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]
})
如何解决此问题并获取考试对象,包括他们的问题?
答案 0 :(得分:2)
出于一些非直观的原因,由于as
属性,这似乎正在发生。要解决此问题,只需删除as
属性:
Exam.hasMany(ExamQuestion);
默认情况下,删除as
属性后,Sequelize会自动添加以下方法:getExam_questions
,addExam_question
等。
他们看起来很糟糕:骆驼和蛇的情况混在一起。
要解决这个问题,我们可以在singular
模型选项(第三个参数)中轻松定义plural
和ExamQuestion
名称:
const ExamQuestion = Sequelize.db.define("exam_question", {
correct_answer: {
type: Sequelize.STRING
},
text: {
type: Sequelize.STRING
}
}, {
name: {
singular: "question",
plural: "questions"
}
});
这将要求Sequelize创建getQuestions
和addQuestion
等方法,而不是getExam_questions
和addExam_question
。