sequelize.jssequelize-typescript

Sequelize include with association name vs. with model name


In sequelize doc, it mentioned that you can use include with model name, e.g.const users = await User.findAll({ include: Task });, and you can use include with association name, e.g.User.findAll({ include: { association: 'Instruments' } }); // Also works. I am wondering if there is a difference between them.

Background is that, I usually use include with model name, but I had to use include with association name because one of table is has two associations referring to the same table. Use model name will cause a multiple alias error. So I am wondering is there a difference between them.


Solution

  • As you already found out the model name does not guarantee a match to a certain association: only if you have one without alias. The association name works like a pair of a model name + an alias:

    association: The association you want to eagerly load. (This can be used instead of providing a model/as pair). So you can use interchangeably:

    User.findAll({ include: { association: 'Instruments' } })
    

    or

    User.findAll({ include: { model: 'Task', as: 'Instruments' } })