简体   繁体   English

与模型序列无关的模型

[英]Model not associated with Model Sequelize

I'm trying to esatblish a One-To-Many relationship between the tables: Exam and Exam_Questions , using Sequelize. 我想esatblish表之间存在一个一对多的关系: ExamExam_Questions ,使用Sequelize。

Even though the tables are created properly and I can see them in PhpMyAdmin, I keep getting the following error in console: 即使表已正确创建,并且可以在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;

To solve the error, I tried: 为了解决该错误,我尝试:

ExamQuestion.belongsTo(Exam);

But that doesn't change anything. 但这并没有任何改变。

The query is: 查询是:

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

How to fix this problem and get the Exam objects including their questions? 如何解决此问题并获取包括他们的问题的考试对象?

TL;DR TL; DR

For some very non-intuitive reason this seems to be happening because of the as property. 由于某些非直觉的原因,这似乎是由于as属性而发生的。 To fix the problem, simply remove the as property: 要解决此问题,只需删除as属性:

Exam.hasMany(ExamQuestion);

Fixing the methods 固定方法

By default, after removing the as property, Sequelize will automagically add the following methods: getExam_questions , addExam_question and so on. 默认情况下,删除as属性后,Sequelize将自动添加以下方法: getExam_questionsaddExam_question等。

They look quite bad: camel and snake cases mixed up together. 它们看起来很糟:骆驼和蛇皮箱混在一起。

To solve that, we can easily define the singular and plural names in the ExamQuestion model options (the third argument): 为了解决这个问题,我们可以在ExamQuestion模型选项(第三个参数)中轻松定义singularplural名称:

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

This will dictate Sequelize to create methods such as getQuestions and addQuestion instead of getExam_questions and addExam_question . 这将要求Sequelize创建诸如getQuestionsaddQuestiongetExam_questions方法,而不是创建getQuestionsaddQuestiongetExam_questions addExam_question

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM