본문으로 바로가기

Eager and Lazy Relations

category DB, ORM/🧊 typeORM 2021. 1. 2. 01:58

github.com/typeorm/typeorm/blob/master/docs/eager-and-lazy-relations.md

 

typeorm/typeorm

ORM for TypeScript and JavaScript (ES7, ES6, ES5). Supports MySQL, PostgreSQL, MariaDB, SQLite, MS SQL Server, Oracle, SAP Hana, WebSQL databases. Works in NodeJS, Browser, Ionic, Cordova and Elect...

github.com

 

- eager

 

별다로 relationship을 설정하지 않아도 eager를 설정하면 자동으로 relationship을 불러옵니다.

@ManyToMany(type => Category, category => category.questions, {
  eager: true
})
Eager relations only work when you use find* methods. If you use QueryBuilder eager relations are disabled and have to use leftJoinAndSelect to load the relation. Eager relations can only be used on one side of the relationship, using eager: true on both sides of relationship is disallowed.

 

find* (즉, find, findAll, findOne...)에서 자동으로 relationship을 불러온다고 알아두면 됩니다.

 

 

- lazy

 

Promise로 반환하면, 자동으로 lazy relationship이 됩니다.

lazy를 불러올 때는 Promise.resolve를 하던가, await로 불러오면 됩니다.

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

categories is a Promise. It means it is lazy and it can store only a promise with a value inside. Example how to save such relation:

const category1 = new Category();
category1.name = "animals";
await connection.manager.save(category1);

const category2 = new Category();
category2.name = "zoo";
await connection.manager.save(category2);

const question = new Question();
question.categories = Promise.resolve([category1, category2]); // resolve
const question = await connection.getRepository(Question).findOne(1);
const categories = await question.categories;
Note: if you came from other languages (Java, PHP, etc.) and are used to use lazy relations everywhere - be careful. Those languages aren't asynchronous and lazy loading is achieved different way, that's why you don't work with promises there. In JavaScript and Node.JS you have to use promises if you want to have lazy-loaded relations. This is non-standard technique and considered experimental in TypeORM.

 

 

darren, dev blog
블로그 이미지 DarrenKwonDev 님의 블로그
VISITOR 오늘 / 전체