如何使用 sequelize 执行此特定 sql 左连接?

How to do this specific sql left join using sequelize?

我尝试使用如下的 sequelize 为投票系统制作数据库结构:

PollAnswer = sequelize.define('PollAnswer', {answer: DataTypes.STRING});
PollQuestion = sequelize.define('PollQuestion', {question: DataTypes.STRING});
VotingHistory = sequelize.define('VotingHistory', {});
User = sequelize.define('User', {name: DataTypes.STRING});

PollAnswer.belongsTo(PollQuestion); //every question has many answers
VotingHistory.belongsTo(PollQuestion);
VotingHistory.belongsTo(PollAnswer);
VotingHistory.belongsTo(User);

我想编写一个查询来接收特定问题的答案及其在 VotingHistory table 中的投票数,我使用以下 sql命令和响应是我所期望的:

select count(VotingHistory.PollAnswerId), PollAnswer.answer from PollAnswers
left join VotingHistories on PollAnswer.id = VotingHistory.PollAnswerId group by PollAnswers.id

预期响应:

answer    count
------------
ans1       10
ass2       2
ans3       0

但是当使用 sequelize 查询同样的东西时,如下所示:

VotingHistory.findAll({
  where:{PollQuestionId: req.params.poll},
  attributes:[[sequelize.fn('count', sequelize.col('PollAnswerId')), 'count']],
  group:['PollAnswerId'],
  include:[{
    model:PollAnswer,
    attributes:['id','answer']
  }]
})

只是returns这个:

answer    count
------------
ans1       10
ass2       2

我的问题是: 我怎样才能得到 以上 sql 命令查询 returns,使用 sequelize 的预期响应?

您应该使用 PollAnswer.findAll、sequelize.fn 并包括 PollHistory,请参阅

不就是一个"typo"吗? attributes 中缺少 r

如果没有,请看以下内容:

您是否尝试记录您的脚本生成的查询?您可以通过在其配置中添加 logging: console.log 来做到这一点:

VotingHistory.findAll({
  logging: console.log,
  where:{PollQuestionId: req.params.poll},
  attributes:[[sequelize.fn('count', sequelize.col('PollAnswerId')), 'count']],
  group:['PollAnswerId'],
  include:[{
    model:PollAnswer,
    attributes:['id','answer']
  }]
})

不过我怀疑你的问题是你使用的是 PollAnswerId 而不是 PollAnswer.id

VotingHistory.findAll({
  logging: console.log,
  where:{PollQuestionId: req.params.poll},
  attributes:[[sequelize.fn('count', sequelize.col('PollAnswer.id')), 'count']],
  group:['PollAnswer.id'],
  include:[{
    model:PollAnswer,
    attributes:['id','answer']
  }]
})