首页 > 解决方案 > TypeORM RelationCount 替代

问题描述

我在一个项目中使用 TypeORM 一段时间。我们有一个拥有以下属性的实体

@RelationCount("sentences")
public sentencesCount?: number;

@OneToMany(() => Sentence, e => e.job)
public sentences?: Sentence[];

但是我注意到它RelationCount已经贬值了

@RelationCount, deprecated 不要使用这个装饰器,它可能会在未来的版本中被移除

我在 TypeORM 官方自述文件中寻找替代品,但除了QueryBuilder使用本机 SQLSELECT COUNT(*)语句创建自定义之外,我什么也没找到。

在这个项目中我们使用了很多简单的语句,比如myRepo.find(). 我宁愿不替换所有这些对QueryBuilders.

我应该@RelationCount在我们的项目中使用什么来代替?

我应该忽略这个“贬值”警告吗??

标签: typescripttypeorm

解决方案


你需要使用loadRelationCountAndMap方法

yourRepository
  .createQueryBuilder("entity")
  .leftJoin('entity.sentences', 'sentences')
  .loadRelationCountAndMap('entity.sentencesCount', 'entity.sentences');

@RelationCount("sentences") public sentencesCount?: number; 并从您的实体类中删除。


推荐阅读