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.
1 2 |
Project.belongsToMany(User, {through: 'UserProject'}); User.belongsToMany(Project, {through: 'UserProject'}); |
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,
1 2 3 4 |
models.User.belongsToMany(models.Building, { through: models.UserBuilding, as: 'buildings' }) |
This will add methods
- getBuildings
- setBuildings
- addBuilding
- addBuildings
to User
like this:
1 2 3 4 |
const user = await ctx.models.User.findByPk(userId, {transaction}) await user.addBuilding(building, { transaction }) await user.getBuildings() await user.setBuildings(params.buildings, {transaction}) |
There are also remove version of the generated methods like so:
- removeBuilding
- removeBuildings
1 |
await user.removeBuilding(building, { transaction }) |