我有自引用Category
模型及相关产品。
class Category < ApplicationRecord
has_many :subcategories,
class_name: 'Category',
foreign_key: 'parent_id'
has_many :products
scope :main, -> { where(parent_id: nil) }
end
为了获得所有主要类别的子类别和产品的数量,想要执行双左外连接。
这是我不使用left_outer_joins
方法的方法。
Category.main
.select('categories.*, COUNT(DISTINCT cats.id) as sub_count, COUNT(products.id) as prod_count')
.joins('LEFT JOIN categories AS cats ON categories.id = cats.parent_id')
.joins('LEFT JOIN products ON cats.id = products.category_id')
.group('categories.name')
我想用left_outer_joins
方法做同样的事情,因为从代码角度看它更清晰。
Category.main
.select('categories.name, COUNT(DISTINCT subcategories_categories.id) as sub_count, COUNT(products.id) as prod_count')
.left_joins(:subcategories, :products)
.group('categories.name')
输出以下查询:
SELECT categories.name, COUNT(DISTINCT subcategories_categories.id) as sub_count, COUNT(products.id) as prod_count
FROM "categories"
LEFT OUTER JOIN "categories" "subcategories_categories" ON "subcategories_categories"."parent_id" = "categories"."id"
LEFT OUTER JOIN "products" ON "products"."category_id" = "categories"."id"
WHERE "categories"."parent_id" IS NULL
GROUP BY categories.name
正如您所看到的那样,问题出现在第二个LEFT OUTER JOIN
,因为它引用了categories
而不是subcategories_categories
。
对于此类方案,是否有left_outer_joins
的解决方法?
答案 0 :(得分:1)
尝试left_outer_joins(subcategories: :products)