Rails ActiveRecord连接两次相同的表

时间:2015-01-26 23:51:39

标签: mysql ruby-on-rails activerecord

我遇到表连接问题。 ActiveRecord生成SQL,它连接同一个表两次。假设我们有模型:

class Product < ActiveRecord::Base
  has_many :characteristics
  has_many :properties, through: :characteristics
  has_many :values, through: :characteristics
end

class Value < ActiveRecord::Base
  has_many :characteristics
end

class Property < ActiveRecord::Base
  has_many :characteristics
end

class Characteristic < ActiveRecord::Base
  belongs_to :product
  belongs_to :property
  belongs_to :value
end

所以我想加入属性和值。 Product.joins(:properties).joins(:values)将生成下一个SQL:

SELECT `products`.*
FROM `products`
INNER JOIN `characteristics` ON `characteristics`.`product_id` = `products`.`id`
INNER JOIN `properties` ON `properties`.`id` = `characteristics`.`property_id`
INNER JOIN `characteristics` `characteristics_products_join` ON `characteristics_products_join`.`product_id` = `products`.`id`
INNER JOIN `values` ON `values`.`id` = `characteristics_products_join`.`value_id`

characteristics有两个相同的连接。我怎么能避免这个?

抱歉我的英文

谢谢

1 个答案:

答案 0 :(得分:0)

我正在寻找更优雅的解决方案并偶然发现了这一点。但这会起作用,而不是像我想的那样Rails-y。

Product.joins(characteristics: :properties)
       .joins('INNER JOIN `characteristics` `characteristics_products_join` ON `characteristics_products_join`.`product_id` = `products`.`id`')
       .joins('INNER JOIN `values` ON `values`.`id` = `characteristics_products_join`.`value_id`')