【问题标题】:Activerecord counting with joinActiverecord 计数与加入
【发布时间】:2018-10-16 22:46:59
【问题描述】:

我有 2 个 activerecord 关系

class Proxy  
   # capacity integer  
   # country string  
   has_many :configs  
end

class Config  
   belongs_to :proxy  
   # proxy_id  
   # port integer 
end

我想在 activerecord 查询中查找特定国家/地区的所有代理,其中容量小于他的配置,并按配置计数器排序。

我的意思是我正在尝试做类似(伪 activrecord 示例)

Proxy.joins(:configs).where(country: country)
                    .where("capacity > ?", :configs.count)
                    .order_by(:configs.count)

我想也许我正纠结于我的问题,它有一个简单的解决方案。

提前致谢!

【问题讨论】:

    标签: ruby-on-rails ruby activerecord


    【解决方案1】:

    尝试在关联中使用:counter_cache

    class Proxy  
     # configs_count integer
     has_many :configs  
    end
    
    class Config  
     belongs_to :proxy, counter_cache: true
    end
    

    然后你可以这样做:

    Proxy.where(country: country)
         .where("capacity > ?", :configs_count)
         .order_by(:configs_count)
    

    【讨论】:

    • 这对我有帮助,因为使选择更轻松,我会做更多的选择而不是添加到配置中。
    【解决方案2】:

    standardSELECT ... JOIN ... GROUP BY ... HAVING ... ORDERSQL任务:

    Proxy.
      joins(:configs).
      group(:id).
      having('proxies.capacity > count(configs.id)').
      order('count(configs.id)')
    

    【讨论】:

      猜你喜欢
      • 2011-08-30
      • 1970-01-01
      • 1970-01-01
      • 2020-05-17
      • 2012-06-07
      • 2021-11-19
      • 2021-05-13
      • 2013-01-19
      • 1970-01-01
      相关资源
      最近更新 更多