Sequelizejs:同时findAll和count关联 [英] Sequelizejs: findAll and count associations at the same time

查看:51
本文介绍了Sequelizejs:同时findAll和count关联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有两个模型:PostComment,现在我可以使用 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关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆