请帮忙。
我正在尝试执行以下 typeorm 查询:
return await getRepository(Company)
.createQueryBuilder("Company")
.leftJoinAndSelect("Company.plants", "Plant")
.leftJoinAndSelect("Plant.documents", "Document")
.leftJoinAndSelect("Plant.notes", "Note")
.loadRelationCountAndMap("Plant.documentsCount", "Plant.documents")
.loadRelationCountAndMap("Plant.notesCount", "Plant.notes")
.getMany();
这个想法是选择每个工厂以及所有公司的所有工厂的文档和注释数量。
(实际上不需要选择笔记和文档本身,但我这样做是为了证明关系确实有效)。
此外,我还指定了占位符变量来在 Plant 实体中保留计数:
@OneToMany(() => Document, (document) => document.plant)
documents: Document[];
documentsCount: number;
@OneToMany(() => Note, (note) => note.plant)
notes: Note[];
notesCount: number;
奇怪的是,返回的 Plant.documentsCount 和 Plant.notesCount 都是 0(而文档和注释的集合不为空并且正在被选择)。
另一个奇怪的事情是,我在 SQL 查询中没有看到任何选择这些计数的尝试,因此我希望 typeorm 本身会进行计数(因为它正确选择了集合)。
有人可以就如何选择这些计数提供一些建议吗?