Skip to content
Toggle navigation
Projects
Groups
Snippets
Help
public
/
sequelize
This project
Loading...
Sign in
Toggle navigation
Go to a project
Project
Repository
Issues
0
Merge Requests
0
Pipelines
Wiki
Snippets
Settings
Activity
Graph
Charts
Create a new issue
Jobs
Commits
Issue Boards
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Charts
不要怂,就是干,撸起袖子干!
Commit 930e6537
authored
Sep 15, 2015
by
Andrew Eddie
Committed by
Jan Aagaard Meier
Oct 08, 2015
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
Added documentation for nested creation (see #3386).
1 parent
d8affcf2
Hide whitespace changes
Inline
Side-by-side
Showing
1 changed file
with
98 additions
and
0 deletions
docs/docs/associations.md
docs/docs/associations.md
View file @
930e653
...
...
@@ -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
Write
Preview
Markdown
is supported
Attach a file
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to post a comment