Typeorm .loadRelationCountAndMap 返回零

2024-04-09

请帮忙。 我正在尝试执行以下 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 是最无能的框架。所有重要功能要么已弃用,要么未实现。

为了解决这个特定问题,我必须:

  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。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Typeorm .loadRelationCountAndMap 返回零 的相关文章

随机推荐