I tried to make a DB structure for voting system using sequelize like below:
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);
I want to write a query to receive the answers of a specific question and their vote counts in VotingHistory table, I did it using folowing sql command and response was what I expected:
select count(VotingHistory.PollAnswerId), PollAnswer.answer from PollAnswers
left join VotingHistories on PollAnswer.id = VotingHistory.PollAnswerId group by PollAnswers.id
expected response:
answer count
------------
ans1 10
ass2 2
ans3 0
But when using sequelize to query the same thing like below:
VotingHistory.findAll({
where:{PollQuestionId: req.params.poll},
attributes:[[sequelize.fn('count', sequelize.col('PollAnswerId')), 'count']],
group:['PollAnswerId'],
include:[{
model:PollAnswer,
attributes:['id','answer']
}]
})
it just returns this:
answer count
------------
ans1 10
ass2 2
my question is: how can I get the expected response that above sql command query returns, using sequelize?