2017-06-16 75 views
0

如何在SQL中編寫此查詢?ActiveRecord整個集合的映射計數,然後查詢到SQL

a = Brand.find(1).publications.map(&:component_id) 
Hash[a.group_by(&:itself).map {|k, v| [Component.find(k).name, v.size] }] 

=> {"title one"=>1, "something"=>1, "continue"=>1} 

很明顯,我不能Ennumerable打電話.to_sql。我至今寫了這個,但它似乎是計算其他的東西比出現次數:

SELECT c.name, c.id, COUNT(p.component_id) 
FROM publications p 
INNER JOIN components c 
ON c.id = p.component_id 
INNER JOIN brands_components bc 
ON bc.brand_id IN (1) 
GROUP BY 1, 2 

這得到了錯誤的號碼(即,太多的是相同的):

name    id  count 
------------------------------ 
something  2026 114 
another name  3028 1,140 
another new one 2409 2,850 
world class  264  6,612 
top up   3370 114 

該模型協會是這樣的:

class Brand < ActiveRecord::Base 
    has_many :documents 
    has_many :publications, through: :users 
    has_many :users 
end 

class User < ActiveRecord::Base 
    has_many :documents, dependent: :destroy 
    has_many :publications, through: :documents, dependent: :destroy 
end 

class Document < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :brand 

    has_many :components, through: :publications 
    has_many :publications, dependent: :destroy 
end 

class Publication < ActiveRecord::Base 
    belongs_to :document 
    belongs_to :component 
end 

class Component < ActiveRecord::Base 
    has_many :publications 
    has_many :documents, through: :publications 
end 

我想返回的component_id出現在PublicationBrand過濾計數在SQL中。

+1

so'Brand' has_many'Users','User' has_many' Documents','Document' has_many' Components',through'Publication'。你想要計算一個品牌的所有組件? –

+1

請發佈型號關係並說明您需要的數據返回 – radha

+0

代碼已更新。 –

回答

0

我已經解決了我的問題:

SELECT c.name, COUNT(p.component_id) 
FROM publications p 
INNER JOIN components c 
ON c.id = p.component_id 
INNER JOIN brands_components bc 
ON c.id = bc.component_id 
AND bc.brand_id IN (1) 
GROUP BY 1 

我忘了讓這場比賽:c.id = bc.component_id。可能幫助某人。