Skip to content

Commit

Permalink
docs(associations): belongs to many create with through table
Browse files Browse the repository at this point in the history
  • Loading branch information
sushantdhiman committed May 24, 2020
1 parent a2dcfa0 commit 6d87cc5
Showing 1 changed file with 49 additions and 2 deletions.
51 changes: 49 additions & 2 deletions docs/manual/advanced-association-concepts/advanced-many-to-many.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ const amidala = User.create({ username: 'p4dm3', points: 1000 });
const queen = Profile.create({ name: 'Queen' });
await amidala.addProfile(queen, { through: { selfGranted: false } });
const result = await User.findOne({
where: { username: 'p4dm3' }
where: { username: 'p4dm3' },
include: Profile
});
console.log(result);
Expand All @@ -79,6 +79,53 @@ Output:
}
```

You can create all relationship in single `create` call too.

Example:

```js
const amidala = await User.create({
username: 'p4dm3',
points: 1000,
profiles: [{
name: 'Queen',
User_Profile: {
selfGranted: true
}
}]
}, {
include: Profile
});

const result = await User.findOne({
where: { username: 'p4dm3' },
include: Profile
});

console.log(result);
```

Output:

```json
{
"id": 1,
"username": "p4dm3",
"points": 1000,
"profiles": [
{
"id": 1,
"name": "Queen",
"User_Profile": {
"selfGranted": true,
"userId": 1,
"profileId": 1
}
}
]
}
```

You probably noticed that the `User_Profiles` table does not have an `id` field. As mentioned above, it has a composite unique key instead. The name of this composite unique key is chosen automatically by Sequelize but can be customized with the `uniqueKey` option:

```js
Expand Down Expand Up @@ -617,4 +664,4 @@ Found game: "Winter Showdown"

So this is how we can achieve a *many-to-many-to-many* relationship between three models in Sequelize, by taking advantage of the Super Many-to-Many relationship technique!

This idea can be applied recursively for even more complex, *many-to-many-to-...-to-many* relationships (although at some point queries might become slow).
This idea can be applied recursively for even more complex, *many-to-many-to-...-to-many* relationships (although at some point queries might become slow).

0 comments on commit 6d87cc5

Please sign in to comment.