我正在尝试从数据库中的每个帖子中获取评论数。但是,以下内容:
Post.includes(:comments).group("posts.id").count("comments.id")
引发mysql错误“未知列comments.id”,因为生成的sql似乎完全忽略了includes():
SELECT COUNT(comments.id) AS count_comments_id, posts.id AS posts_id
FROM `posts` GROUP BY posts.id
有趣的是,将 includes() 替换为 joins() 将产生有效的 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