高效使用 Query Builder
避免 N+1 查询问题
N+1 查询问题出现在系统为取回的每一行数据都执行了过多子查询的时候。
要避免它,你可以用 leftJoinAndSelect 或 innerJoinAndSelect 在单条查询中合并多张表,而不是执行多条查询。
const users = await dataSource
.getRepository(User)
.createQueryBuilder("user")
.leftJoinAndSelect("user.posts", "post")
.getMany()这里,leftJoinAndSelect 帮助你用一条查询取回用户的所有帖子,而不是许多条小查询。
只需要原生数据时使用 getRawMany()
在不需要完整对象的场景下,你可以用 getRawMany() 获取原生数据,避免 TypeORM 处理过多信息。
const rawPosts = await dataSource
.getRepository(Post)
.createQueryBuilder("post")
.select("post.title, post.createdAt")
.getRawMany()用 select 限制字段
为了优化内存占用并减少不必要的数据,请用 select 只选取所需字段。
const users = await dataSource
.getRepository(User)
.createQueryBuilder("user")
.select(["user.name", "user.email"])
.getMany()Avoiding the N+1 Query Problem
The N+1 Query Problem occurs when the system executes too many sub-queries for each row of data retrieved.
To avoid this, you can use leftJoinAndSelect or innerJoinAndSelect to combine tables in a single query instead of executing multiple queries.
const users = await dataSource
.getRepository(User)
.createQueryBuilder("user")
.leftJoinAndSelect("user.posts", "post")
.getMany()Here, leftJoinAndSelect helps retrieve all user posts in a single query rather than many small queries.
Use getRawMany() when only raw data is needed
In cases where full objects aren't required, you can use getRawMany() to fetch raw data and avoid TypeORM processing too much information.
const rawPosts = await dataSource
.getRepository(Post)
.createQueryBuilder("post")
.select("post.title, post.createdAt")
.getRawMany()Limit fields using select
To optimize memory usage and reduce unnecessary data, select only the required fields using select.
const users = await dataSource
.getRepository(User)
.createQueryBuilder("user")
.select(["user.name", "user.email"])
.getMany()