鑑於電影和演員在m:n關係。我想要做的就是找回角色名單,由他們扮演的電影數量排序DataMapper:通過關聯計數排序結果(相關對象的數量)
class Movie
include DataMapper::Resource
property :id, Serial
property :title, String
has n, :actors, through: Resource
end
class Actor
include DataMapper::Resource
property :name, String, key: true
has n, :movies, through: Resource
end
在僞DM我想是這樣的:
Actor.all order: [ :movies.count ]
我發現了另一個問題關於通過關聯的單個屬性進行排序,但此方法僅適用於真實屬性。任何可用的解決方案都會有幫助謝謝!
如果您想從該數據返回一個散列,就像下面這樣簡單:'actors = repository(:default).adapter.select( 「SELECT actors.name,count(actor_movies.actor_name)AS count」+ 「 FROM演員「+ 」JOIN actor_movies WHERE actors.name = actor_movies.actor_name「 + 」GROUP BY actors.name「 + 」ORDER BY計數(actor_movies.actor_name)降序「 + 」LIMIT 5;「 ).MAP {|結構| {:name => struct.name,:count => struct.count}}' –