Sequelizejs: findAll and count associations at the same time

被刻印的时光 ゝ 提交于 2019-12-05 16:25:37

You can do something like this:

var attributes = Object.keys(Post.attributes);
var sequelize = Post.sequelize;

attributes.push([sequelize.literal('(SELECT COUNT(*) FROM "Comments" where "Comments"."postId" = "Post"."postId")'), 'commentsCount']);

var query = {
  attributes: attributes,
  include: [{model: Comment}]
}
Post.findAndCountAll(query)
  .then(function(posts){
    ...
  })

It is very much possible with findAndCountAll method provided by the sequelize

Once you make a query by Post.findAndCountAll({include: [{model: Comment, as: 'comments'}]})

by doing post.comments.length you can get the count of comments of each post.

In case, if you would like to find the count of a single post use

Post.findAndCount({where: {id: postId}}, include:[{model: Comments, as: 'comments'}]}) which returns {count: <#comments>, rows: [<Post>]}

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!