简体   繁体   English

可以通过活动记录中的关联计数来订购吗?

[英]Possible to order by the count of an association in active record?

Lets say I have Posts with many Comments 让我们说我的Posts有很多Comments

Is it possible to do an ActiveRecord query to to get the Posts ordered by most comments? 是否可以执行ActiveRecord查询以获取大多数评论所订购的帖子?

I'm surprised this relatively common query in plain old MySQL doesn't seem to have an easy answer in AR. 我很惊讶这个相对常见的查询在普通的旧MySQL中似乎没有一个简单的答案在AR。 Yes you can use a counter_cache, but this isn't really recreating the original query. 是的,您可以使用counter_cache,但这并不是真正重新创建原始查询。

What am I missing? 我错过了什么?

Taking it one step further. 更进一步。 What if Posts have many Comments which have many Likes . 如果Posts有很多Comments有很多Likes怎么办? Is it possible to get Posts with the most Likes in aggregate? 是否有可能获得总数最多的帖子?

Thanks! 谢谢!

As you say, counter_cache seems to be the closest to doing it the "rails way". 正如你所说,counter_cache似乎最接近“轨道方式”。 So far I have not encountered any AR defined methods for this specific purpose but this is the closest thing to it that I have seen: 到目前为止,我没有遇到任何针对此特定目的的AR定义方法,但这是我所看到的最接近它的方法:

@posts = Post.select("posts.*, COUNT(comments.id) AS count_comments").joins("LEFT OUTER JOIN comments ON posts.id = comments.post_id").group("posts.id").order("count_comments DESC")

@posts.each do |post|
  puts "Comments: #{post.count_comments}"
end

Custom select to include the count_comments attribute. 自定义选择以包含count_comments属性。 Joins instead of include because include will override the select syntax. 加入而不是include,因为include将覆盖select语法。 Custom joins syntax instead of merely :comments because otherwise it will be an inner join which will prevent posts without comments to be retrieved. 自定义连接语法而不仅仅是:注释,否则它将是一个内连接,它将阻止检索没有注释的帖子。

This is basically writing the entire SQL syntax yourself, but still... it works :) 这基本上是自己编写整个SQL语法,但仍然......它的工作原理:)

Pretty sure you can do something like this as well if you want: 如果你想要,你可以确定你也可以这样做:

posts = Post.find(:all, :include => 'comments')
posts.sort { |a,b| b.comments.count <=> a.comments.count }

I supose you can do something like this using arel:: 我想你可以用arel做这样的事情::

comments= Comment.arel_table
posts= Post.joins(:comments).order(comments[:id].count)

Though, I am not sure if this is the right way to do it. 虽然,我不确定这是否是正确的方法。 You will have to try it by yourself. 你必须自己尝试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM