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

Commit 72b97eff by Jan Aagaard Meier

Merge pull request #3758 from bulkan/docs/foreignKey-option-belongsToMany

Document `foreignKey` option on belongsToMany & `where` for include
2 parents 84e37c14 0f3143b7
......@@ -143,10 +143,10 @@ Defining `through` is required. Sequelize would previously attempt to autogenera
This will add methods `getUsers`, `setUsers`, `addUsers` to `Project`, and `getProjects`, `setProjects` and `addProject` to `User`.
Sometimes you may want to rename your models when using them in associations. Let's define users as workers and projects as tasks by using the alias (`as`) option:
Sometimes you may want to rename your models when using them in associations. Let's define users as workers and projects as tasks by using the alias (`as`) option. We will also manually define the foreign keys to use:
```js
User.belongsToMany(Project, { as: 'Tasks', through: 'worker_tasks' })
Project.belongsToMany(User, { as: 'Workers', through: 'worker_tasks' })
User.belongsToMany(Project, { as: 'Tasks', through: 'worker_tasks', foreignKey: 'userId' })
Project.belongsToMany(User, { as: 'Workers', through: 'worker_tasks', foreignKey: 'projectId' })
```
Of course you can also define self references with belongsToMany:
......
......@@ -1075,6 +1075,51 @@ User.findAll({ include: [{ model: Tool, as: 'Instruments' }] }).then(function(us
})
```
When eager loading we can also filter the associated model using `where`. This will return all
`User`s in which the `where` clause of `Tool` model matches rows.
```js
User.findAll({ include: [{ model: Tool, as: 'Instruments', where: {name: {$like: '%ooth%'}} }] })
.then(function(users) {
console.log(JSON.stringify(users))
/*
[{
"name": "John Doe",
"id": 1,
"createdAt": "2013-03-20T20:31:45.000Z",
"updatedAt": "2013-03-20T20:31:45.000Z",
"Instruments": [{
"name": "Toothpick",
"id": 1,
"createdAt": null,
"updatedAt": null,
"UserId": 1
}]
}],
[{
"name": "John Smith",
"id": 2,
"createdAt": "2013-03-20T20:31:45.000Z",
"updatedAt": "2013-03-20T20:31:45.000Z",
"Instruments": [{
"name": "Toothpick",
"id": 1,
"createdAt": null,
"updatedAt": null,
"UserId": 1
}]
}],
*/
})
```
When an eager loaded model is filtered using `include.where` then `include.required` is implicitly set to
`true`. This means that an inner join is done returning parent models with any matching children.
### Including everything
To include all attributes, you can pass a single object with `all: true`:
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!