Rails:在没有原始SQL的连接表列上使用group()



我有一个小问题与分组ActiveRecord::关系。我正在尝试通过连接表列分组查询,而不使用原始SQL。

现在的代码是这样的:

Sale::Product.joins(stock_product::supplier).group('core_suppliers.id').first

结果:

Sale::Product Load (42989.5ms)  SELECT  `sale_products`.* FROM `sale_products` INNER JOIN `stock_products` ON `stock_products`.`deleted_at` IS NULL AND `stock_products`.`id` = `sale_products`.`stock_product_id` INNER JOIN `core_suppliers` ON `core_suppliers`.`id` = `stock_products`.`core_supplier_id` GROUP BY core_suppliers.id ORDER BY `sale_products`.`id` ASC LIMIT 1

我尝试使用merge:

来解决这个问题。
Sale::Product.joins(stock_product: :supplier).merge(::Core::Supplier.group(:id)).first

结果:

Sale::Product Load (32428.4ms)  SELECT  `sale_products`.* FROM `sale_products` INNER JOIN `stock_products` ON `stock_products`.`deleted_at` IS NULL AND `stock_products`.`id` = `sale_products`.`stock_product_id` INNER JOIN `core_suppliers` ON `core_suppliers`.`id` = `stock_products`.`core_supplier_id` GROUP BY `sale_products`.`core_supplier_id` ORDER BY `sale_products`.`id` ASC LIMIT 1

我不明白为什么Active::Record不按合并表的列分组我的关联。特别是因为这种方法适用于' ' ' order()````。

事先感谢您的帮助

您可以尝试在Rails 3中引入的Arel库,用于构建SQL查询。

::Core::Supplier.group(core_supplier: :id)替换为::Core::Supplier.arel_table[:id]:

Sale::Product.joins(stock_product::supplier).group(::Core::Supplier.arel_table[:id]).first

如果你不想使用Arel你可以直接在查询中隐藏Arel在ApplicationRecord中实现如下:

class ApplicationRecord < ActiveRecord::Base
def self.[](attribute)
arel_table[attribute]
end
end

然后你的查询可以重写成这样:

Sale::Product.joins(stock_product::supplier).group(::Core::Supplier[:id]).first

最新更新