Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node.js sequelize associations, include on condition

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?

like image 707
Johny Avatar asked May 31 '13 20:05

Johny


1 Answers

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
  }]
})
like image 141
veeresh yh Avatar answered Nov 14 '22 19:11

veeresh yh