TypeORM 中处理 N+1 查询问题的方法:
-
使用 relations 选项加载关联数据:
typescriptuserRepository.find({ relations: ['posts', 'profile'] }); -
使用 join 和 leftJoinAndSelect:
typescriptcreateQueryBuilder('user') .leftJoinAndSelect('user.posts', 'post') .leftJoinAndSelect('user.profile', 'profile') .getMany(); -
使用 FindOptions 的关系加载:
typescriptuserRepository.find({ relations: { posts: true, profile: true } }); -
避免在循环中查询: 不要在 forEach 或 map 循环中单独查询关联数据,应该在主查询中一次性加载。
-
使用 DataLoader(适用于 GraphQL): 对于复杂的批量查询场景,可以使用 DataLoader 进行数据批处理和缓存。
最佳实践是始终在查询时明确指定需要加载的关联数据,避免延迟加载导致的 N+1 问题。