按关联计数产品belongs_to

时间:2009-11-19 02:09:17

标签: ruby-on-rails activerecord

班级销售

belongs_to :product, :accessible => true
belongs_to :brand, :accessible => true

end

Class Product

has_many :sales
belongs_to :brand

end

Class Brands

has_many :products
  has_many :sales

end

我如何获得产品销售最多的品牌?

1 个答案:

答案 0 :(得分:1)

如果你想继续使用activerecord,你可以使用Calculations,但需要2个查询来完成它:

>> brands = Sale.count(:id, :include => :brand, :group=> 'sales.brand_id', :limit => 5)
  SQL (0.7ms)   SELECT count(DISTINCT `sales`.id) AS count_id, sales.brand_id AS sales_brand_id FROM `sales` LEFT OUTER JOIN `brands` ON `brands`.id = `sales`.brand_id GROUP BY sales.brand_id LIMIT 5
=> #<OrderedHash {967032312=>3, 1392881137=>1}>

>> brands_with_most_sales = Brand.find(brands.keys)
  Brand Load (0.5ms)   SELECT * FROM `brands` WHERE (`brands`.`id` = 967032312) 
=> [#<Brand id: 967032312, title: "brand-x", created_at: "2009-11-19 02:46:48", updated_at: "2009-11-19 02:46:48">]

否则您可能希望使用find_by_SQL

编写自己的查询