gpt4 book ai didi

mysql - 计算 Rails 中的关联记录

转载 作者:可可西里 更新时间:2023-11-01 06:27:47 24 4
gpt4 key购买 nike

我正在尝试从数据库中的每个帖子中获取评论数。但是,以下内容:

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

有趣的是,用 joins() 替换 includes() 将生成有效的 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

最佳答案

includes 方法不会在所有情况下都进行连接,而是出于性能原因批量获取关联(参见 Rails :include vs. :joins)。

你需要做的是一个连接,你几乎在正确的路径上,但组子句有点错误:

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() 在我的 Rails 3.2 上返回 Hash),因此您可以在 View 中循环遍历实际的 post 对象并访问属性 comment_count

关于mysql - 计算 Rails 中的关联记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11077632/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com