【问题标题】:Sequelizejs: findAll and count associations at the same timeSequelize:同时findAll和count关联
【发布时间】:2017-05-19 12:54:50
【问题描述】:
假设我有两个模型:Post和Comment,现在我可以使用Post.findAll()获取所有帖子,但我还需要每个帖子的评论数,我可以循环使用post.countComments()得到计数,但是否有可能在一个查询中做到这一点?谢谢
【问题讨论】:
标签:
node.js
orm
sequelize.js
【解决方案1】:
sequelize提供的findAndCountAll方法很有可能
一旦您通过Post.findAndCountAll({include: [{model: Comment, as: 'comments'}]})进行查询
通过post.comments.length,您可以获得每个帖子的cmets计数。
如果您想查找单个帖子的使用次数
Post.findAndCount({where: {id: postId}}, include:[{model: Comments, as: 'comments'}]})
返回{count: <#comments>, rows: [<Post>]}
【解决方案2】:
你可以这样做:
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){
...
})