Sequelize Belongs to Many

Belongs-To-Many associations

Belongs-To-Many associations are used to connect sources with multiple targets. Furthermore the targets can also have connections to multiple sources.

This will create a new model called UserProject with the equivalent foreign keys projectId and userId. Whether the attributes are camelcase or not depends on the two models joined by the table (in this case User and Project).

Defining through is required. Sequelize would previously attempt to autogenerate names but that would not always lead to the most logical setups.

This will add methods

  • getUsers
  • setUsers
  • addUser
  • addUsers

to Project, and

  • getProjects
  • setProjects
  • addProject
  • addProjects

to User

Similarly,

This will add methods

  • getBuildings
  • setBuildings
  • addBuilding
  • addBuildings

to User

like this:

There are also remove version of the generated methods like so:

  • removeBuilding
  • removeBuildings