问题
Is it possible to pass a condition in the include array of a findAll query?
For example I have UsersModel, PostsModel and UserVotesModel.
Users can vote on posts.
For the logged in user I want to query posts and include only the vote for the current user. I am not able to do this using Sequelize's include param. Sequelize joins posts and UserVotes on postId, but for this specific query I want to join on both postId and UserId.
Any ideas how to solve this problem?
回答1:
If you include a model with a where condition ( that will default require to true) but if you mark it as false to LEFT OUTER JOIN the association
Post.findAll({
where: {
user_id: current_user_id
},
include: [
{
model: UserVote,
where: {
'user_id': current_user_id
},
required: false
}]
})
回答2:
I just checked Sequelize source code. This is not possible!
来源:https://stackoverflow.com/questions/16865190/node-js-sequelize-associations-include-on-condition