简体   繁体   中英

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.

Even though the tables are created properly and I can see them in PhpMyAdmin, I keep getting the following error in console:

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

For some very non-intuitive reason this seems to be happening because of the as property. To fix the problem, simply remove the as property:

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.

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):

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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