如何按 has_many 关系中的对象数量对 Rails AR.find 进行排序 [英] How to sort Rails AR.find by number of objects in a has_many relationship
本文介绍了如何按 has_many 关系中的对象数量对 Rails AR.find 进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何编写 AR 查找查询以按 has_many 关联中的记录数对结果进行排序?
How can I write an AR find query to have the results ordered by the number of records in a has_many association?
class User < ActiveRecord::Base
has_many :photos
end
我想做类似...
User.find(:all, :order => photos.count)
我意识到我的发现不是有效代码.假设我有以下数据.
I realize my find is not valid code. Say I have the following data.
User 1, which has 3 photos
User 2, which has 5 photos
User 3, which has 2 photos
我希望我的发现按...的顺序将我带回用户
I want my find to bring me back the users in the order of...
User 2,
User 1,
User 3
基于用户照片的数量
推荐答案
如果你不想要额外的列,你总是可以在返回的结果集中要求额外的列:
If you don't want an extra column, you could always ask for an extra column in the returned result set:
User.all(:select => "#{User.table_name}.*, COUNT(#{Photo.table_name}.id) number_of_photos",
:joins => :photos,
:order => "number_of_photos")
这会生成以下 SQL:
This generates the following SQL:
SELECT users.*, COUNT(photos.id) number_of_photos
FROM `users` INNER JOIN `photos` ON photos.user_id = users.id
ORDER BY number_of_photos
这篇关于如何按 has_many 关系中的对象数量对 Rails AR.find 进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文