Emanuela Colta
Emanuela Colta

Reputation: 2207

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?

Upvotes: 1

Views: 467

Answers (1)

Ionică Bizău
Ionică Bizău

Reputation: 113465

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.

Upvotes: 2

Related Questions