Skip to content

Commit 3e52060

Browse files
committed
feat: Add information on extra attributes on join table in N:M relationships
1 parent aa2d151 commit 3e52060

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

versioned_docs/version-6.x.x/advanced-association-concepts/advanced-many-to-many.md

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -368,6 +368,44 @@ Person.belongsToMany(Person, { as: 'Children', through: 'PersonChildren' })
368368
// This will create the table PersonChildren which stores the ids of the objects.
369369
```
370370

371+
## Associations with extra attributes on through table
372+
373+
When creating an N:M association, for example, with User and Project through UserProjects you might want extra attributes in the join table like the "role" attribute . This relationship can be setup like this:
374+
375+
```js
376+
const User = sequelize.define('User', {
377+
username: DataTypes.STRING,
378+
}, { timestamps: false });
379+
380+
const Project = sequelize.define('Project', {
381+
name: DataTypes.STRING
382+
}, { timestamps: false });
383+
384+
const UserProjects = sequelize.define('UserProjects', {
385+
role: DataTypes.STRING
386+
}, { timestamps: false });
387+
388+
User.belongsToMany(Project, { through: UserProjects})
389+
Project.belongsToMany(User, { through: UserProjects})
390+
```
391+
392+
Creating multiple associations with the same extra attributes is possible by passing a single object on the through attribute:
393+
```js
394+
user1.setProjects([project1, project2, project3], { through: { role: 'admin' }})
395+
```
396+
397+
Setting different extra attributes per association can be done by passing an array of objects of the same length as the ammount of associations:
398+
```js
399+
user1.setProjects([project1, project2, project3], {
400+
through: [
401+
{ role: 'admin' },
402+
{ role: 'manager' },
403+
{ role: 'designer' },
404+
]
405+
})
406+
```
407+
408+
371409
## Specifying attributes from the through table
372410

373411
By default, when eager loading a many-to-many relationship, Sequelize will return data in the following structure (based on the first example in this guide):

0 commit comments

Comments
 (0)