wam
w__am 개발노트
wam
  • 분류 전체보기 (165)
    • CS 지식 (10)
      • 자료구조 (0)
      • 알고리즘 (0)
      • 컴퓨터 구조 (0)
      • 운영체제 (0)
      • 네트워크 (7)
      • 데이터베이스 (0)
      • 디자인 패턴 (3)
    • Frontend (131)
      • Three.js (64)
      • NPM (1)
      • Nest.js (19)
      • React (10)
      • Apollo (7)
      • TypeScript (2)
      • JavaScript (12)
      • HTML, CSS (1)
      • Jest (3)
      • E2E (5)
      • Cypress (7)
    • Database (12)
      • TypeORM (12)
    • IT 지식 (8)
      • 클라우드 서비스 (3)
      • 네트워크 (1)
      • 데이터 포맷 (2)
      • 기타 (2)
    • IT Book (2)
    • 유용한 사이트 (1)

블로그 메뉴

  • 홈
  • 태그
  • 방명록
  • 🐱 Github

인기 글

태그

  • 데이터 포맷
  • math.cos()
  • 원형적인 움직임
  • reactive variables
  • 렌더링 성능 최적화
  • three.js 구성 요소
  • 함수 리터럴
  • react 성능 최적화
  • 함수 표현식
  • 오프-프레미스(off-premise) 방식
  • gridhelper
  • threejs 개발 할 때 도움을 줄 수 있는 유틸리티
  • 스코프
  • 삼각함수
  • type-graphql
  • getelapsedtime()
  • 함수 선언문
  • mapped types
  • axeshelper
  • getdelta()
  • 함수의 범위
  • 초기 환경설정
  • Decorators
  • 디자인 패턴
  • API
  • math.sin()
  • Interface
  • joi 에러
  • e.preventdefault()
  • isabstract

최근 글

관리자

글쓰기 / 스킨편집 / 관리자페이지
hELLO · Designed By 정상우.
wam

w__am 개발노트

relationship 옵션 ( eager relationships, Lazy relations)
Frontend/Nest.js

relationship 옵션 ( eager relationships, Lazy relations)

2024. 8. 24. 18:17

 

eager relationships

@ManyToMany(type => Category, category => category.questions, {
eager: true
})

@JoinTable()
categories: Category[];
  • Eager relation은 데이터베이스에서 엔티티를 로드할 때마다 자동으로 relation 필드들을 로드한다.
  • 너무 많은걸 load 하면 서버 부하가 심하므로 주의해야 한다.
// 나쁜예 - 많은 정보를 load 하고 있다.
subscription {
  cookedOrders {
    restaurant {
      name
    }
    total
    customer {
      email
      restaurants {
        owner {
          email
          restaurants {
            name
          }
        }
      }
    }
  }
}

 

 

eager relationships예시

@Field(() => Restaurant, { nullable: true })
@ManyToOne(() => Restaurant, (restaurant) => restaurant.orders, {
  onDelete: "SET NULL",
  nullable: true,
  eager: true,
})
restaurant?: Restaurant;
  • 주문을 받을 때마다 자동으로 relationship이 load 된다.
  • entity에 옵션을 넣어주면 된다.

 

 

Lazy relations

@ManyToMany(type => Question, question => question.categories)
questions: Promise< Question[]>;

@ManyToMany(type => Category, category => category.questions)
@JoinTable()
categories: Promise< Category[]>;

// 원하는 rellationship을 await 해야 한다.
const question = await connection.getRepository(Question).findOne(1);
const categories = await question.categories;
  • Lazy relation은 한 번 access 하면 load 된다.
  • Lazy relation은 해당 필드에 접근하면 로드된다.
  • Lazy relation은 타입으로 Promise를 가져야 한다.
  • Promise에 값을 저장하고 로드할 때도 Promise를 반환한다.

 

 

Lazy relations 예시

const order = await this.orders.findOne({ where: { id: orderId } });

const order = await this.orders.findOne({
  where: { id: orderId },
  relations: ["restaurant", "customer", "driver"],
});
await order.restaurant;
  • order에서 레스토랑을 load 하고 싶다면 await order.restaurant을 꼭 해줘야 한다.

 

 

 

저작자표시 변경금지 (새창열림)

'Frontend > Nest.js' 카테고리의 다른 글

Task Scheduling  (0) 2024.08.26
REST와 GraphQL: Controller와 Resolver의 차이점 이해하기  (0) 2024.07.30
NestJS의 기본 모듈 구조  (0) 2024.07.30
GraphQL 스키마에서 enum 타입을 정의할 때 사용, registerEnumType  (0) 2024.07.29
GraphQL 스키마를 정의할 때 매우 유용한 도구 MapperType  (0) 2024.07.29
    'Frontend/Nest.js' 카테고리의 다른 글
    • Task Scheduling
    • REST와 GraphQL: Controller와 Resolver의 차이점 이해하기
    • NestJS의 기본 모듈 구조
    • GraphQL 스키마에서 enum 타입을 정의할 때 사용, registerEnumType
    wam
    wam

    티스토리툴바