1 | initial version |
You can use the include
option in Sequelize to specify which associations you want to include in the result when performing a search with a where
clause.
Here is an example:
const User = db.define('user', {
name: Sequelize.STRING,
})
const Post = db.define('post', {
title: Sequelize.STRING,
body: Sequelize.TEXT
})
const Comment = db.define('comment', {
body: Sequelize.TEXT
})
// associations
User.hasMany(Post)
Post.belongsTo(User)
Post.hasMany(Comment)
Comment.belongsTo(Post)
// search with where clause and include associations
const posts = await Post.findAll({
where: {
id: 1
},
include: [
{
model: User,
attributes: ['id', 'name']
},
{
model: Comment,
include: [
{
model: User,
attributes: ['id', 'name']
}
]
}
]
})
In this example, we are searching for a post with id 1
and including the User
and Comment
associations with their respective attributes. The Comment
association also includes the User
association with their respective attributes.
This will return a result set that includes all the associated data for the post, the user who created it, and all the comments with their associating users.