Eager relations are loaded automatically each time you load entities from the database. - TypeORM 공식문서
아래는 간단예시
//user.entity.ts
export class User {
@OneToMany((type) => Eager, (eager) => eager.user)
eagers: Eager[];
}
//eager.entity.ts
export class Eager {
@ManyToOne((type) => User, (user) => user.eager,
eager: true,
})
user?: User;
...
}
eager:true
인 Eager의 entity도 함께 불러와진다.export class UserSrvice {
constructor (
@InjectRepisitory(User) private readonly users: Repository<User>
){}
...
async testUser () {
const user = await this.users.findOne({ where : id, relations : ["eagers"] })
}
...
}
단, eager relation을 쓸 때는 nest가 제공하는 pagination 기능을 사용할 수 없다.
Lazy Relation의 경우 entity에 접근할때 로드되며 Promise를 반환하기 때문에 await로 받아와야 한다.
Entities in lazy relations are loaded once you access them. Such relations must have Promise as type - you store your value in a promise, and when you load them a promise is returned as well. - TypeORM 공식문서
//user.entity.ts
export class User {
@OneToMany((type) => Lazy, (lazy) => lazy.user)
lazy: Promise<lazy[]>;
}
//eager.entity.ts
export class Lazy {
@ManyToOne((type) => User, (user) => user.lazy)
user?: Promise<User>;
...
}
export class UserSrvice {
constructor (
@InjectRepisitory(User) private readonly users: Repository<User>
){}
...
async testUser () {
const user = await this.users.findOne({ where : id })
//await로 relation에 접근해야 한다
cosnt lazy = await user.lazy
}
...
}