sequelize mysql中的嵌套查询以获取upvote和downvote计数

sequelize mysql中的嵌套查询以获取upvote和downvote计数,mysql,node.js,express,sequelize.js,Mysql,Node.js,Express,Sequelize.js,我正在尝试对一个帖子进行向上投票和向下投票,该帖子有答案关联的表格,并将投票分为与答案关联的表格 const posts = await Posts.findAll({ include: [{ model: Answers, include: [{ attributes: { include: [[Sequelize.fn("COUNT", Sequelize.col("id&

我正在尝试对一个帖子进行向上投票和向下投票,该帖子有答案关联的表格,并将投票分为答案关联的表格

const posts = await Posts.findAll({
    include: [{
        model: Answers,
        include: [{
          attributes: { 
              include: [[Sequelize.fn("COUNT", Sequelize.col("id")), "votesCount"]] 
          },
          model: Votes, attributes: []
        }]
    }]
});
这是我的投票模式

const Votes = sequelize.define('votes', {
    id:{
        type:Sequelize.INTEGER,
        autoIncrement:true,
        allowNull:false,
        primaryKey:true
      },
      answerId: {
        type: Sequelize.INTEGER,
        allowNull:false,
         references: {
          model: 'answers',
          key: 'id'
        }
      },
      userId: {
        type: Sequelize.INTEGER,
        allowNull:false,
         references: {
          model: 'users',
          key: 'id'
        }
      },
      voteType: { type: Sequelize.BOOLEAN, allowNull:false },
      createdAt: Sequelize.DATE,
      updatedAt: Sequelize.DATE
})
voteTypetrue表示向上投票,false表示向下投票

有什么办法可以通过Sequelize获得结果吗

期待着这样的事情

[{
            "id": 1,
            "userId": 15,
            "title": "The standard Lorem Ipsum passage, used since the 1500s",
            "description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor i",
            "answers": [
                {
                    "id": 1,
                    "postId": 1,
                    "userId": 33,
                    "ans": "Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia",
                }
            ],
            votes: {
                upVote: 5,
                downVote: 1
            }
        },]

您可以尝试使用
Sequelize.literal
通过使用子查询获取这两个计数:

const posts = await Posts.findAll({
    include: [{
        model: Answers,
        include: [{
          attributes: { 
              include: [
  [Sequelize.literal("(SELECT COUNT(*) FROM Votes WHERE answerId=answer.id AND Votes.voteType=true)"), "upVote"],
  [Sequelize.literal("(SELECT COUNT(*) FROM Votes WHERE answerId=answer.id AND Votes.voteType=false)"), "downVote"]
          ] 
          }
        }]
    }]
});

似乎您需要使用
Sequelize.literal
来使用subqueries@Anatoly你能帮我举个例子吗?谢谢老兄,你救了我一天