不要怂,就是干,撸起袖子干!

Commit 6d87cc58 by Sushant

docs(associations): belongs to many create with through table

1 parent a2dcfa07
...@@ -52,7 +52,7 @@ const amidala = User.create({ username: 'p4dm3', points: 1000 }); ...@@ -52,7 +52,7 @@ const amidala = User.create({ username: 'p4dm3', points: 1000 });
const queen = Profile.create({ name: 'Queen' }); const queen = Profile.create({ name: 'Queen' });
await amidala.addProfile(queen, { through: { selfGranted: false } }); await amidala.addProfile(queen, { through: { selfGranted: false } });
const result = await User.findOne({ const result = await User.findOne({
where: { username: 'p4dm3' } where: { username: 'p4dm3' },
include: Profile include: Profile
}); });
console.log(result); console.log(result);
...@@ -79,6 +79,53 @@ Output: ...@@ -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: 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 ```js
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!