相关疑难解决方法(0)

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
Run Code Online (Sandbox Code Playgroud)

所以我想加入属性和值。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` = …
Run Code Online (Sandbox Code Playgroud)

mysql activerecord ruby-on-rails

5
推荐指数
1
解决办法
1197
查看次数

如何多次连接同一个表

我正在使用postgresql.

我有一个名为custom_field_answers的表.数据看起来像这样.

Id | product_id | value      | number_value | 
4  | 2          |            | 117          |
3  | 1          |            | 107          |
2  | 1          | bangle     |              |
1  | 2          | necklace   |              |
Run Code Online (Sandbox Code Playgroud)

我想找到所有产品,其text_value为'bangle',number_value小于50.

SELECT p.*
FROM "products" AS p
INNER JOIN "custom_field_answers" AS a1 ON p."id" = a1."product_id"
INNER JOIN "custom_field_answers" AS a2 ON p."id" = a1."product_id" 
WHERE a1."value" = 'bangle' AND a2."number_value" < 50
Run Code Online (Sandbox Code Playgroud)

我尝试使用以下代码生成该sql.

conditions = <conditions from arel>
relation = self.scoped …
Run Code Online (Sandbox Code Playgroud)

ruby-on-rails

0
推荐指数
1
解决办法
1785
查看次数

标签 统计

ruby-on-rails ×2

activerecord ×1

mysql ×1