Typeorm .loadRelationCountAndMap 返回零

时间:2023-02-06
本文介绍了Typeorm .loadRelationCountAndMap 返回零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

请帮忙.我正在尝试执行以下 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();

我们的想法是选择每个工厂以及所有公司的所有工厂的文档和笔记数量.(实际上不需要自己选择笔记和文件,但我这样做是为了证明关系确实有效).

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 实体中保持计数:

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 查询中没有看到任何选择这些计数的尝试,因此我希望 typeorm 本身可以进行计数(因为它正确选择了集合).

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?

推荐答案

不幸的是 Typeorm 是最无能的框架.所有重要功能都已弃用或未实现.

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. 选择集合本身:

   .leftJoinAndSelect("Plant.documents", "Document")
   .leftJoinAndSelect("Plant.notes", "Note")

  1. 添加计算和冗余关系数组删除:

  @AfterLoad()
  getDocumentsCount() {
    this.documentsCount = this.documents.length;
    delete this.documents;
  }

  @AfterLoad()
  getNotesCount() {
    this.notesCount = this.notes.length;
    delete this.notes;
  }

  1. 决定永远不再使用 TypeORM.

这篇关于Typeorm .loadRelationCountAndMap 返回零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:如何将“2016-07-01 01:12:22 PM"转换为“2016-07-01 13:12:22" 下一篇:Typeorm 不返回所有数据

相关文章

最新文章