如何用ActiveRecord实现与指定分组统计SQL相同的输出结果?
实现对应SQL的ActiveRecord写法
你给出的SQL用了LEFT JOIN,会返回所有帖子(哪怕没有评论),并按标题分组统计对应评论相关的行数。但你用的joins(:comments)是内连接,只会返回有评论的帖子,结果自然和原SQL不一致。
要实现完全匹配的效果,分两步来:
1. 修正模型关联
因为原SQL的关联条件是posts.title = comments.post_title(不是默认的主键外键关联),所以需要在模型里指定关联字段:
# app/models/post.rb class Post < ApplicationRecord has_many :comments, foreign_key: :post_title, primary_key: :title end # app/models/comment.rb class Comment < ApplicationRecord belongs_to :post, foreign_key: :post_title, primary_key: :title end
2. 编写ActiveRecord查询
Rails 5及以上版本(推荐)
用left_joins实现左连接,再分组统计:
Post.left_joins(:comments).group(:title).count('comments.*')
Rails 5以下版本
直接写SQL片段来指定左连接:
Post.joins('LEFT JOIN comments ON posts.title = comments.post_title').group('posts.title').count('comments.*')
这两种写法生成的SQL都会和你给出的原始查询一致,返回所有帖子标题及对应的统计数。
内容的提问来源于stack exchange,提问作者Sig
相关产品推荐
相关产品推荐

