Sequelize hasMany Join association Sequelize hasMany Join association sqlite sqlite

Sequelize hasMany Join association


The issue is that the relation has to be defined both ways. Currently, Sequelize knows how to get from Food -> Meal because of

db.food.hasMany(db.meal, {as : 'Food', foreignKey : 'idFood'});

but it does not know how to get from Meal -> Food. That's why you have to define the same relation the other way round, like so:

db.meal.belongsTo(db.food, {foreignKey : 'idFood'});

This does not add any new keys since it would define meal.idFood which you defined with your first statement already.

Now you should be able to execute

db.meal.findAll({ include : [db.food] }).then(function (meals) {    console.log(JSON.stringify(meals)); <-- each array element of meals should have an attribute `food`});


If you are using an alias on the association ({ as: 'Food' }) you need to use it on the include statement as well.

So it'd be like that:

db.meal.findAll({   include : [{    model: db.food,    as: 'Food'  }]}).then(function (meals) {  console.log(JSON.stringify(meals));});

If an association is aliased (using the as option), you must specify this alias when including the model. Notice how the user's Tools are aliased as Instruments above. In order to get that right you have to specify the model you want to load, as well as the alias

More information here.