【问题标题】:Rails Active Record query count multiple relationsRails Active Record 查询计数多个关系
【发布时间】:2014-04-16 17:06:55
【问题描述】:

我的数据库结构如下:

  • 群组 has_many 包
  • 包有_many 个房间
  • 房间有_and_belongs_to_many 客户

好的。每个房间都可以是“四人房”、“三人房”、“双人房”等。我可以通过 Group.rooms 访问属于某个组的所有房间。

我希望能够获得集团拥有的每种房间类型的客户数量。

例如:

  • 四:16 个客户端
  • 双:10 个客户端 *等等。

我设法获得了每种类型的房间数量,如下所示:

Group.rooms.group('type').count

有什么想法吗?

更新 1 - 模型

Quarto.rb(房间)

class QuartoContratado < ActiveRecord::Base
    belongs_to :pacote
    has_and_belongs_to_many :clientes, :join_table => :acomodacoes

Pacote.rb(包)

class Pacote < ActiveRecord::Base        
    belongs_to :grupo
    has_many :passageiros
    has_many :clientes, :through => :passageiros
    has_many :quartos, :class_name => "QuartoContratado"

Grupo.rb(组)

class Grupo < ActiveRecord::Base
    has_many :pacotes
    has_many :clientes, :through => :pacotes, :conditions => { :pacotes => { :cancelado => false } }
    has_many :quartos, :class_name => "QuartoContratado", :through => :pacotes, :conditions => { :pacotes => { :cancelado => false } }

Client.rb(客户端)

class Cliente < ActiveRecord::Base
    has_many :passageiros
    has_many :pacotes, :class_name => "Pacote", :through => :passageiros
    has_many :grupos, :through => :pacotes, :conditions => { :pacotes => { :cancelado => false } }

【问题讨论】:

  • 继续发布您的所有模型,以便我们可以看到实际的关系。
  • 我已经用@Lumbee 模型更新了问题

标签: mysql sql ruby-on-rails activerecord


【解决方案1】:

这就是我设法得到我想要的东西的方法......它看起来很丑!有没有更好的写法?

group = Grupo.first
types = group.quartos.group_by { |t| t.type }

types.each do |key, value|
   print "#{key} - "
   c=0
   value.each do |v|
    c= c+v.clientes.count
   end
   puts "#{c} clients"
 end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-14
    • 2013-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多