通过连接表按关联计数排序

时间:2015-04-30 17:25:26

标签: sql ruby-on-rails postgresql activerecord

我有一个有许多剧集的节目,剧集中有许多人通过贡献。 (见下图)

我已将has_many :people, through: :contributions添加到Show,因此我可以:game_of_thrones.people.count,甚至:

  has_many :actors, -> { joins(:roles).merge(Role.actors).distinct },
    through: :contributions, source: :person

-

game_of_thrones.actors.count

但我想做的是在game_of_thrones或breaking_bad等上创建一个演员列表,按演出次数排序。

示例:

  1. Jon Snow:9集
  2. Arya Stark:8集
  3. Joffrey Lannister:5集
  4. Tyrion Lannister:2集
  5. Database schema of a Show with many Episodes.  Episodes has many people through contributions.

    我的问题是两个人。

    1. 如何根据贡献计数返回节目中的顶级演员列表?

    2. 我应该通过ActiveRecord还是SQL查询来执行此操作。什么是更好地理解这一点的好参考,所以我可以停止打扰堆栈溢出?

      class Show < ActiveRecord::Base
        has_many :episodes, inverse_of: :show
        has_many :contributions, through: :episodes
        has_many :people, through: :contributions
      
        has_many :actors, -> { joins(:roles).merge(Role.actors) },
          through: :contributions, source: :person
      end
      
      class Episode < ActiveRecord::Base
        belongs_to :show, inverse_of: :episodes
        has_many :contributions, inverse_of: :episode
        has_many :roles, through: :contributions
        has_many :people, through: :contributions
      end
      
      class Contribution < ActiveRecord::Base
        belongs_to :episode, inverse_of: :contributions
        belongs_to :person, inverse_of: :contributions
        belongs_to :role, inverse_of: :contributions
      end
      
      class Person < ActiveRecord::Base
        has_many :contributions, inverse_of: :person
        has_many :episodes, through: :contributions
        has_many :roles, through: :contributions
      
        scope :actors, -> { joins(:roles).merge(Role.actors) }
      end
      
      class Role < ActiveRecord::Base
        has_many :contributions, inverse_of: :role
        has_many :people, through: :contributions
        has_many :episodes, through: :contributions
      
        scope :actors, -> { where(name: 'Actor') }
      end
      
    3. 查询失败:game_of_thrones.people.joins(:contributions).distinct.joins(:episodes).where("episodes.show_id = 1").order("count(episodes.show_id) desc")

      game_of_thrones.guests.joins(:contributions).order("count(contribuions.id) desc")
      

0 个答案:

没有答案
相关问题