問題描述
請幫忙.我正在嘗試執(zhí)行以下 typeorm 查詢:
please help. I am trying to execute the following typeorm query:
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();
我們的想法是選擇每個工廠以及所有公司的所有工廠的文檔和筆記數(shù)量.(實際上不需要自己選擇筆記和文件,但我這樣做是為了證明關(guān)系確實有效).
The idea was to select counts of documents and notes per each plant along with all plants for all companies. (Actually selecting notes and documents themselves was not needed, but i did it to prove that relations do work).
此外,我還指定了占位符變量以在 Plant 實體中保持計數(shù):
Also I have specified the placeholder variables to keep counts in Plant entity:
@OneToMany(() => Document, (document) => document.plant)
documents: Document[];
documentsCount: number;
@OneToMany(() => Note, (note) => note.plant)
notes: Note[];
notesCount: number;
奇怪的是返回的Plant.documentsCount和Plant.notesCount都是0(而文檔和筆記的集合不是空的,正在被選中).
Strangely the returned Plant.documentsCount and Plant.notesCount are 0 (while the collections of documents and notes are not empty and are being selected).
另一件奇怪的事情是,我在 SQL 查詢中沒有看到任何選擇這些計數(shù)的嘗試,因此我希望 typeorm 本身可以進行計數(shù)(因為它正確選擇了集合).
Another strange thing is that i don't see in SQL querires any attempts to select these counts, thus i hope typeorm itself would do counting (since it has collections selected correctly).
有人可以就如何選擇這些計數(shù)提供一些建議嗎?
Could anybody please give some advise on how to select these counts?
推薦答案
不幸的是 Typeorm 是最無能的框架.所有重要功能都已棄用或未實現(xiàn).
Unfortunately Typeorm is the most impotent framework. All important features are either deprecated or not implemented.
為了解決這個特定問題,我必須:
To solve this particular issue i had to:
- 選擇集合本身:
.leftJoinAndSelect("Plant.documents", "Document")
.leftJoinAndSelect("Plant.notes", "Note")
- 添加計算和冗余關(guān)系數(shù)組刪除:
@AfterLoad()
getDocumentsCount() {
this.documentsCount = this.documents.length;
delete this.documents;
}
@AfterLoad()
getNotesCount() {
this.notesCount = this.notes.length;
delete this.notes;
}
- 決定永遠不再使用 TypeORM.
這篇關(guān)于Typeorm .loadRelationCountAndMap 返回零的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!