整个集合的ActiveRecord映射计数,然后将该查询映射到SQL
如何用SQL编写此查询整个集合的ActiveRecord映射计数,然后将该查询映射到SQL,sql,ruby-on-rails,activerecord,Sql,Ruby On Rails,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上调用。\u 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
上调用。\u 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
这会得到错误的数字(即太多相同的数字):
模型关联如下所示:
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
class品牌
我想返回由SQL中的品牌过滤的出版物上组件id
的出现次数。我已经解决了我的问题:
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\u id
。可能会帮助某人。因此品牌
有很多用户
,用户
有很多文档
,文档
有很多组件
。你想对一个品牌的所有组件进行计数吗?请发布模型关系,并说明你需要的数据是什么,backCode已经更新。
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