Sequelize Eager Loading Error

Viewed 15387

I'm getting an issue where include in my query isn't working, and I can't figure out why. I have two models: Question and Suggestion.

Question:
var Question = sequelize.define('Question', {
  }, {
    classMethods: {
      associate: function (models) {
        // associations can be defined here
        Question.belongsTo(models.User, {
          as: 'askerId',
          foreignKey: 'askerId'
        })

        Question.belongsTo(models.User, {
          as: 'winnerId',
          foreignKey: 'winnerId'
        })

        Question.hasMany(models.Suggestion)
        Question.hasMany(models.TagQuestion)
      }
    }
  })

Suggestion:

var Suggestion = sequelize.define('Suggestion', {
    text: DataTypes.STRING
  }, {
    classMethods: {
      associate: function (models) {
        // associations can be defined here
        Suggestion.belongsTo(models.Question, {
          foreignKey: 'questionId',
          as: 'question'
        })

        Suggestion.belongsTo(models.User)

        Suggestion.hasMany(models.Vote)
      }
    }
  })

And my attempted query is here:

Question.findAll({
    include: [{
      model: models.Suggestion
    }]
  })

But I keep getting the error: SequelizeEagerLoadingError: Suggestion is not associated to Question!

Why are they not associated? They are in my database (based on my migration that I wrote). And how should I set up my associations if I am currently doing it incorrectly? I've looked at other people with this issue and not been able to figure out why my associations are wrong.

3 Answers

I ran into this error because I had a bad syntax. I was using

include: {
  model: db.modelOne,
  model: db.modelTwo
}

without the brackets []. Including it solved the error. Anyway, the mentioned docs give this much cleaner option to include all the foreign models recursively:

User.findAll({ include: [{ all: true, nested: true }]});

Please check out your init-models.js, code like this:

  question.hasMany(suggestion, { as: 'suggestion', foreignKey: 'questionId'});
  suggestion.belongsTo(question, { as: 'question', foreignKey: 'questionId'});

is exist ?

from

"sequelize": "^6.6.2"
Related