请帮忙。 我正在尝试执行以下 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 本身会进行计数(因为它正确选择了集合)。
有人可以就如何选择这些计数提供一些建议吗?
不幸的是,Typeorm 是最无能的框架。所有重要功能均已弃用或未实现。
为了解决这个特定问题,我必须:
.leftJoinAndSelect("Plant.documents", "Document")
.leftJoinAndSelect("Plant.notes", "Note")
@AfterLoad()
getDocumentsCount() {
this.documentsCount = this.documents.length;
delete this.documents;
}
@AfterLoad()
getNotesCount() {
this.notesCount = this.notes.length;
delete this.notes;
}
不幸的是,我的项目被迫使用
typeorm
。您可以尝试以下方法:
@Expose()
documentsCount() {
return this.documents.length;
}
@Expose()
notesCount() {
return this.notes.length;
}
讨论: 但看起来你正在做一个API?你应该返回这个数组(
leftjoin
的文档和注释),然后前端可以使用.length
进行自计算。目前前端已经很强大了,会和服务器分担负担。
.leftJoinAndSelect("Plant.documents", "Document")
.leftJoinAndSelect("Plant.notes", "Note")