How to define an association to a model with array of foreign keys using sequelize with postgres How to define an association to a model with array of foreign keys using sequelize with postgres mongoose mongoose

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:

  1. Teams
this.belongsToMany(models.users, { through: 'TeamUsers' }); 
  1. 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.