我對 ActiveRecord::Relation 進行分組有一個小問題。我試圖在不使用原始 SQL 的情況下通過連接表列對 quary 進行分組。
目前的代碼如下所示:
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()```。
提前感謝您的幫助
uj5u.com熱心網友回復:
您可以嘗試Arel使用 Rails 3 中引入的庫來構建 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,您可以像這樣在 ApplicationRecord 中隱藏Arel實作:
class ApplicationRecord < ActiveRecord::Base
def self.[](attribute)
arel_table[attribute]
end
end
而且您的查詢可以這樣重寫:
Sale::Product.joins(stock_product::supplier).group(::Core::Supplier[:id]).first
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/487404.html
