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

Commit 930e6537 by Andrew Eddie Committed by Jan Aagaard Meier

Added documentation for nested creation (see #3386).

1 parent d8affcf2
Showing with 98 additions and 0 deletions
......@@ -635,6 +635,104 @@ Series.hasOne(Video);
Trainer.hasMany(Series);
```
## Creating with associations
An instance can be created with nested association in one step, provided all elements are new.
### Creating elements of a "BelongsTo" or "HasOne" association
Consider the following models:
```js
var Product = this.sequelize.define('Product', {
title: Sequelize.STRING
});
var User = this.sequelize.define('User', {
first_name: Sequelize.STRING,
last_name: Sequelize.STRING
});
Product.belongsTo(User);
// Also works for `hasOne`
```
A new `Product` and `User` can be created in one step in the following way:
```js
return Product.create({
title: 'Chair',
User: {
first_name: 'Mick',
last_name: 'Broadstone'
}
}, {
include: [ User ]
});
```
### Creating elements of a "BelongsTo" association with an alias
The previous example can be extended to support an association alias.
```js
var Creator = Product.belongsTo(User, {as: 'creator'});
return Product.create({
title: 'Chair',
creator: {
first_name: 'Matt',
last_name: 'Hansen'
}
}, {
include: [ Creator ]
});
```
### Creating elements of a "HasMany" or "BelongsToMany" association
Let's introduce the ability to associate a project with many tags. Setting up the models could look like:
```js
var Tag = this.sequelize.define('Tag', {
name: Sequelize.STRING
});
Product.hasMany(Tag);
// Also works for `belongsToMany`.
```
Now we can create a project with multiple tags in the following way:
```js
Product.create({
id: 1,
title: 'Chair',
Tags: [
{ name: 'Alpha'},
{ name: 'Beta'}
]
}, {
include: [ Tag ]
})
```
And, we can modify this example to support an alias as well:
```js
var Categories = Product.hasMany(Tag, {as: 'categories'});
Product.create({
id: 1,
title: 'Chair',
categories: [
{id: 1, name: 'Alpha'},
{id: 2, name: 'Beta'}
]
}, {
include: [ Categories ]
})
```
***
[0]: https://www.npmjs.org/package/inflection
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!