SQL Server Typeorm .loadRelationCountAndMap returns zeros

qxgroojn  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(104)

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();

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).

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;

Strangely the returned Plant.documentsCount and Plant.notesCount are 0 (while the collections of documents and notes are not empty and are being selected).

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).

Could anybody please give some advise on how to select these counts?

svmlkihl

svmlkihl1#

Unfortunately Typeorm is the most impotent framework. All important features are either deprecated or not implemented.

To solve this particular issue i had to:

  1. Select collections themselves:
.leftJoinAndSelect("Plant.documents", "Document")
   .leftJoinAndSelect("Plant.notes", "Note")
  1. Add calculations and redundant relation array deletion:
@AfterLoad()
  getDocumentsCount() {
    this.documentsCount = this.documents.length;
    delete this.documents;
  }

  @AfterLoad()
  getNotesCount() {
    this.notesCount = this.notes.length;
    delete this.notes;
  }
  1. Decided to never ever use TypeORM.

相关问题