본문 바로가기

개발-문제해결/Nestjs

typeorm - relations cascade

문제

 

테이블이 테이블1-테이블2-테이블3 형태로 된 상태에서 테이블1, 테이블2, 테이블3 의 정보를 leftjoin 해야하는 상황

 

해결

- querybuilder 사용

 

tableA - tableB3 - tableC 의 정보가 필요할 경우 아래와 같이 leftJoin을 사용해준다.

const qb = this.studyRepository
      .createQueryBuilder('tableA')
      .leftJoinAndSelect('tableA.tableB1', 'tableB1')
      .leftJoinAndSelect('tableA.tableB2', 'tableB2')
      .leftJoinAndSelect('tableA.tableB3', 'tableB3', )
      .leftJoinAndSelect('tableA.tableB4', 'tableB4')
      .leftJoinAndSelect('tableB3.tableC', 'tableC') // tableB3.tableC 이렇게 불러준다.
      .where('tableA.id = :tableAId', { tableAId })

 

 

- find 함수 사용시

 

relations 항목을 연달아 사용해준다.

 

const found = await this.studyRepository
	.findOne(
		tableAId,
		{relations: ['tableB1', 'tableB2', 'tableB3', 'tableB3.tableC']}
	)

'개발-문제해결 > Nestjs' 카테고리의 다른 글

nestjs - leftJoinAndMapOne  (0) 2021.08.26