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 |