我正在尝试获取数据库中每个帖子的评论数量。然而,以下内容:
Post.includes(:comments).group("posts.id").count("comments.id")引发mysql错误"Unknown column comments.id",因为生成的sql似乎完全忽略了includes():
SELECT COUNT(comments.id) AS count_comments_id, posts.id AS posts_id
FROM `posts` GROUP BY posts.id有趣的是,将include()替换为join()将产生有效的sql:
Post.joins(:comments).group("posts.id").count("comments.id")
SELECT COUNT(comments.id) AS count_comments_id, posts.id AS posts_id
FROM `posts` INNER JOIN `comments` ON `comments`.`post_id` = `posts`.`id`
GROUP BY posts.id但是上面的查询排除了所有评论为0的帖子,这不是我想要的。我需要的是生成下面的SQL (但不写SQL,他/他)
SELECT COUNT(comments.id) AS count_comments_id, posts.id AS posts_id
FROM `posts` LEFT OUTER JOIN `comments` ON `comments`.`post_id` = `posts`.`id`
GROUP BY posts.id发布于 2012-06-18 16:02:01
出于性能原因(请参阅Rails :include vs. :joins),includes方法不会在所有情况下都执行连接,而是批量获取关联。
你需要做的是连接,并且你几乎在正确的路径上,但是把group子句弄错了:
Post.select("posts.*, COUNT(comments.id) as comment_count").joins("LEFT OUTER JOIN comments ON (comments.post_id = posts.id)").group("posts.id")请注意,此解决方案具有实际返回Post对象的好处(使用.count()返回my Rails 3.2上的Hash ),因此您可以在视图中遍历实际的post对象,还可以访问属性comment_count。
发布于 2017-11-30 13:44:11
现在这个问题实际上要简单得多:
Comment.joins(:post).group(:post_id).count(:post_id)这将为您提供{<post_id> => <count of comments>}的地图
发布于 2012-06-18 14:12:53
试试这个:
Post.select("COUNT(comments.id) AS count_comments_id, posts.id AS posts_id").
includes(:comments).group("posts.id")https://stackoverflow.com/questions/11077632
复制相似问题