我想從數據庫中的每個帖子獲取評論數。然而以下,:計算Rails中的關聯記錄
Post.includes(:comments).group("posts.id").count("comments.id")
引發MySQL錯誤 「未知列comments.id」 時,由於生成的sql似乎完全忽略包括():
SELECT COUNT(comments.id) AS count_comments_id, posts.id AS posts_id
FROM `posts` GROUP BY posts.id
有趣的是,取代包括()與連接()會產生工作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
正確,但INNER JOIN排除了所有沒有評論的帖子。我需要的是完整的帖子列表,計算的字段(即comment_count)在適當的情況下設置爲0 – Giuseppe
請查看我自己的答案以瞭解我的意思。將明確的LEFT JOIN添加到您的解決方案似乎不起作用。所有帶有0條評論的結果都彙總爲一條,不知道爲什麼。 – Giuseppe
因爲它是由comments.id分組的。由於所有沒有評論的評論都有評論。只需將group子句更改爲'posts.id',它應該沒問題。 我更新了答案 – Tigraine