Sequelize.js:同时查找和计数所有关联 [英] Sequelizejs: findAll and count associations at the same time

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

问题描述

说我有两个模型: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

推荐答案

使用续集提供的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>]}

这篇关于Sequelize.js:同时查找和计数所有关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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