Methods to handle the N+1 query problem in TypeORM:
-
Use the relations option to load related data:
typescriptuserRepository.find({ relations: ['posts', 'profile'] }); -
Use join and leftJoinAndSelect:
typescriptcreateQueryBuilder('user') .leftJoinAndSelect('user.posts', 'post') .leftJoinAndSelect('user.profile', 'profile') .getMany(); -
Use FindOptions for relationship loading:
typescriptuserRepository.find({ relations: { posts: true, profile: true } }); -
Avoid querying in loops: Do not query related data individually in forEach or map loops; load all needed data in the main query at once.
-
Use DataLoader (suitable for GraphQL): For complex batch query scenarios, use DataLoader for data batching and caching.
Best practice is to always explicitly specify the related data to be loaded when querying, avoiding N+1 problems caused by lazy loading.