node.js sequelize associations, include on condition

核能气质少年 提交于 2019-12-23 11:45:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!