问题描述
假设我有两个模型:Post
和 Comment
,现在我可以使用 Post.findAll()
来获取所有帖子,但是我还需要每个帖子的评论计数,我可以循环并使用 post.countComments()
来获取计数,但是可以在一个查询中做到这一点吗?谢谢
say I have two models: Post
and Comment
, now I can use Post.findAll()
to get all posts, but I also need the comment count of each post, I can make a loop and use post.countComments()
to get the count, but is it possible to do that in one query? thanks
推荐答案
sequelize提供的findAndCountAll
方法很有可能
It is very much possible with findAndCountAll
method provided by the sequelize
一旦你通过 Post.findAndCountAll({include: [{model: Comment, as: 'comments'}]}) 进行查询
通过post.comments.length
可以得到每篇文章的评论数.
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'}]})
返回 {count: <#comments>, rows: [<Post>]}
这篇关于Sequelizejs:同时findAll和count关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!