如何在TypeORM中获取多关联关系?需扩展关联查询范围
TypeORM 中获取多层关联关系的方法
针对你需要获取category及更多嵌套关联的需求,以下是几种可行的实现方式:
1. 嵌套对象格式的 relations 参数
如果你的Category实体还关联了其他实体(比如父分类、标签等),可以直接在relations的category字段下嵌套定义需要加载的关联:
const announcement = await this.announsRequestsRepo.findOne({ where: { id }, relations: { owner: true, category: { parentCategory: true, // 加载category关联的父分类 tags: true // 加载category关联的标签集合 } } })
2. 字符串数组格式的 relations 参数
用.表示关联层级,写法更简洁,适合多层嵌套场景:
const announcement = await this.announsRequestsRepo.findOne({ where: { id }, relations: ["owner", "category", "category.parentCategory", "category.tags"] })
3. 使用 QueryBuilder 实现复杂关联查询
如果需要对关联数据添加过滤条件(比如只加载状态为启用的标签),推荐使用QueryBuilder的leftJoinAndSelect方法:
const announcement = await this.announsRequestsRepo .createQueryBuilder("announcement") .leftJoinAndSelect("announcement.owner", "owner") .leftJoinAndSelect("announcement.category", "category") .leftJoinAndSelect("category.tags", "tag", "tag.isEnabled = :isEnabled", { isEnabled: true }) .where("announcement.id = :id", { id }) .getOne()
注意事项
- 确保你的实体类中已经通过
@ManyToOne、@OneToMany等装饰器正确定义了所有关联关系,否则无法加载对应的关联数据。 - 如果关联层级过深,建议按需加载,避免不必要的性能开销。
内容的提问来源于stack exchange,提问作者Sharl Shaboyan
相关产品推荐
相关产品推荐

