Sequelize js获取相关模型的计数

时间:2015-02-13 07:20:08

标签: sql sequelize.js

比方说,我有一个discussions表和replies表。

如何获得每条讨论记录的回复计数?

Models.course_discussions.count({
    where: { 'course_id': 105 },
    include: [
        {model: Models.course_discussions_replies, as: 'replies'}
    ]
})
.then(function (discussions) {
    if (!discussions) {
        reply(Hapi.error.notFound());
    } else {
        console.log("91283901230912830812 " , discussions);
    }
});

以上代码转换为以下查询 -

SELECT COUNT(`course_discussions`.`id`) as `count` FROM `course_discussions` LEFT OUTER JOIN `course_discussions_replies` AS `replies` ON `course_discussions`.`id` = `replies`.`discussion_id` WHERE `course_discussions`.`course_id`=105;

以上代码让我了解了讨论情况。但是,如何获得每次讨论的回复计数?

以下sql查询有效,但如何以续集方式编写?

SELECT COUNT(  `replies`.`discussion_id` ) AS  `count` 
FROM  `course_discussions` 
LEFT OUTER JOIN  `course_discussions_replies` AS  `replies` ON  `course_discussions`.`id` =  `replies`.`discussion_id` 
WHERE  `course_discussions`.`course_id` =105

1 个答案:

答案 0 :(得分:-2)

如果您需要讨论和回复计数,.replies.length可能适合您。

Models.course_discussions.findAll(
  where: { 'course_id': 105 },
  include: [
    {model: Models.course_discussions_replies, as: 'replies'}
  ]
})
.then(function (discussions) {
  // each discussion in discussions will have a
  // replies array

  discussions[0].repies.length // replies for current discussion
});