使用Node / Sequelize(MySQL)获取包含模型的数量

时间:2019-05-15 08:08:29

标签: javascript mysql node.js sequelize.js

我正在尝试获取问题中包含的答案之类的数字。

此处显示示例

question: { text: "text...", answers: [{likes: []}, {likes: []},{likes: []}]

我想根据这些喜欢的次数对答案进行排序。

以下是查询:

const question = await Question.findOne({
      where: { id },
      attributes: [
        "text",
        "createdAt",
        "updatedAt",
        "id",
        [
          Sequelize.literal(
            `(SELECT COUNT(*) FROM answers WHERE questionId = ${id})`
          ),
          "answerCount"
        ]
      ],
      include: [
        { model: User },
        {
          model: Answer,
          attributes: [
            [
              Sequelize.fn(
                `SQL HERE`
              ),
              "likesCount"
            ]
          ],
          include: [
            { model: User },
            { model: Like, include: { model: User } },
            { model: Comment, include: { model: User } }
          ],
          limit: perPage,
          offset: perPage * (page - 1)
        }
      ]
    });

0 个答案:

没有答案