itsource

여러 테이블이 레일에서 결합

mycopycode 2023. 10. 19. 22:18
반응형

여러 테이블이 레일에서 결합

아래의 mysql 쿼리를 레일 액티브 레코드에 어떻게 쓰나요?

select
    A.*,
    B.* 
from
    raga_contest_applicants_songs AS A 
    join
        raga_contest_applicants AS B 
        ON B.contest_applicant_id = A.contest_applicant_id 
    join
        raga_contest_rounds AS C 
        ON C.contest_cat_id = B.contest_cat_id 
WHERE
    C.contest_cat_id = contest_cat_id 
GROUP BY
    C.contest_cat_id    

두 개의 테이블에 조인을 쓰는 방법은 알고 있지만, 세 개의 테이블에 조인을 사용하는 방법에 대해서는 그다지 자신이 없습니다.

질문에 나온 SQL 쿼리를 다시 쓰려면 다음과 같이 해야 한다고 생각합니다(모델 관계를 완전히 시각화하는 데 어려움을 겪고 있으므로 이는 약간의 추측입니다).

RagaContextApplicantsSong.
  joins(:raga_contest_applicants => [:raga_content_rounds], :contest_cat).
  group('raga_contest_rounds.contest_cat_id')

...그렇게 해서joinsmethod는 두 join 뿐만 아니라 두 join 모두를 돌봅니다.WHERE조항, 그리고 마침내 뒤에.group불러.

참고할 만한 더 많은 정보:

동일한 모델에 여러 개의 연관성을 결합하는 경우 간단히 나열할 수 있습니다.

Post.joins(:category, :comments)
Returns all posts that have a category and at least one comment

중첩 테이블을 결합하는 경우 해시에 있는 것처럼 나열할 수 있습니다.

Post.joins(:comments => :guest)
Returns all comments made by a guest

중첩 연관, 다중 수준:

Category.joins(:posts => [{:comments => :guest}, :tags])
Returns all posts with their comments where the post has at least one comment made by a guest

다음과 같이 ActiveRecord Query Interface 호출을 체인으로 연결할 수도 있습니다.

Post.joins(:category, :comments)
...produces the same SQL as...
Post.joins(:category).joins(:comments)

다른 모든 것이 실패할 경우 항상 SQL 조각을 메소드로 직접 전달하여 작업 쿼리에서 보다 ARQI 중심적인 것으로 전환할 수 있습니다.

   Client.joins('LEFT OUTER JOIN addresses ON addresses.client_id = clients.id')
=> SELECT clients.* FROM clients LEFT OUTER JOIN addresses ON addresses.client_id = clients.id

언급URL : https://stackoverflow.com/questions/16131201/multiple-table-joins-in-rails

반응형