How to define an association to a model with array of foreign keys using sequelize with postgres
Defining associations between models are very simple, as you can find it here.
I can see that you already have the associate
method in each model.You should add this in each method in order to have the correct associations:
- Teams
this.belongsToMany(models.users, { through: 'TeamUsers' });
- Users
this.belongsToMany(models.teams, { through: 'TeamUsers' });
Also, you don't need the Teams
property in the Users model, since many-to-many associations exploit an external table in relational databases.
Here is an example of how to include users when querying for teams:
models.teams.find({ include: models.users}).then(foundTeamsWithUsers => { // Handle here your teams: use users to access the list of users related to each team}).catch(handleErrorFunction);
You can find more examples about eager loading with sequelize.