postgresql을 사용하고 있습니다.한 번 이상 같은 테이블에 가입하는 방법
custom_field_answers라는 테이블이 있습니다. 데이터는 다음과 같습니다.
Id | product_id | value | number_value |
4 | 2 | | 117 |
3 | 1 | | 107 |
2 | 1 | bangle | |
1 | 2 | necklace | |
는 내가 코드를 다음과 같이 그 SQL을 생산하기 위해 노력 미만 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
'팔찌'와 NUMBER_VALUE으로 TEXT_VALUE 한 모든 제품을 찾고 싶어요.
conditions = <conditions from arel>
relation = self.scoped
conditions.each do |condition|
relation = relation.merge(where(condition))
end
joins(:custom_field_answers).merge(relation)
relation.to_a
이 SQL은 (맨 위에 언급 한) 원하는 SQL과 유사하지 않습니다 볼 수 있듯이이 SQL
SELECT "products".* FROM "products" INNER JOIN "custom_field_answers"
ON "custom_field_answers"."product_id" = "products"."id"
WHERE ("custom_field_answers"."value" ILIKE 'bangle')
AND ("custom_field_answers"."number_value" < 50)
다음 생성합니다.
는 나는 아직도이relation = self.scoped
conditions.each do |condition|
relation = relation.merge(where(condition).joins(:custom_field_answers))
end
relation.to_a
행운처럼 조금을 코드 조인 이동했습니다.
누구나 각 관계에 대해 새로운 조인을 강제하는 방법을 알고 있습니다. 레일 3.1.1을 사용하고 있습니다.