TypeORM 对表进行 COUNT 查询,将两个表映射在一起

And*_*rit 3 mysql database typeorm nestjs

我有两个实体ModelVideo主要Video存储有关视频的信息和Model有关模型的信息。因为每个视频可以有多个模型,每个模型可以有多个视频实体,如下所示:

我的实体和表格是什么样子的:

// Video Entity
@Entity()
export class Video {
  @PrimaryGeneratedColumn()
  id?: number; 

  @Column({ charset: 'utf8mb4', collation: 'utf8mb4_unicode_ci' })
  name: string;

  @Column({ type: 'text', charset: 'utf8mb4', collation: 'utf8mb4_unicode_ci' })
  description: string;

  @ManyToMany((type) => Model)
  @JoinTable()
  models: Model[];
}


// Model Entity
@Entity()
export class Model {

  @PrimaryGeneratedColumn()
  id?: number; 

  @Column()
  name: string;

  @Column()
  code: string;
}
Run Code Online (Sandbox Code Playgroud)

由于模型和视频之间存在关系,@ManyToManyTypeORM 还创建了一个额外的表来连接这两者。表名称是video_models_model,它看起来像这样:

+-----------+---------+
| videoId   | modelId |
+===========+=========+
| 1         | 107     |
+-----------+---------+
| 2         | 142     |
+-----------+---------+
| 3         | 91      |
+-----------+---------+
Run Code Online (Sandbox Code Playgroud)

我需要的:

基于 modelId 我需要找出COUNT()视频。在常规查询语言中,它会类似于:

SELECT model.*, COUNT(model_videos.videoId) as totalVideos FROM model as model
LEFT JOIN `video_models_model` `model_videos` ON `model_videos`.`modelId`=`model`.`id` 
WHERE model.id = 1;
Run Code Online (Sandbox Code Playgroud)

我尝试过的:

常规查询如下所示:
this.modelRepository
  .createQueryBuilder('model')  
  .where('model.id = :id', { id: id })        
  .getOne();
Run Code Online (Sandbox Code Playgroud)

所以我所做的被添加到Model实体中

  @ManyToMany(type => Video)
  @JoinTable()
  videos: Video[];
Run Code Online (Sandbox Code Playgroud)

之后我尝试了

this.modelRepository
  .createQueryBuilder('model')
  .leftJoin('model.videos', 'videos')
  .select('COUNT(videos)', 'totalVideos')  
  .where('model.id = :id', { id: id })        
  .getOne();
Run Code Online (Sandbox Code Playgroud)

但它对我来说根本不起作用,而且它还创建了一个名为model_videos_video和columnsmodelId的附加表videoId。所以基本上是重复的video_models_model表。

有什么方法可以使用 TypeORM 进行简单的查询吗?

And*_*rit 8

我发现我必须更改我的实体以使它们是双向的:视频实体:

@Entity()
export class Video {
  @PrimaryGeneratedColumn()
  id?: number; 

  @Column({ charset: 'utf8mb4', collation: 'utf8mb4_unicode_ci' })
  name: string;

  @Column({ type: 'text', charset: 'utf8mb4', collation: 'utf8mb4_unicode_ci' })
  description: string;

  @ManyToMany(type => Model, model => model.videos)
  @JoinTable()
  models: Model[];
}
Run Code Online (Sandbox Code Playgroud)

模型实体:

@Entity()
export class Model {

  @PrimaryGeneratedColumn()
  id?: number; 

  @Column()
  name: string;

  @Column()
  code: string;

  @ManyToMany(type => Video, video => video.models)
  videos: Video[];
}
Run Code Online (Sandbox Code Playgroud)

之后我进行这样的查询:

this.modelRepository
  .createQueryBuilder('model')
  .loadRelationCountAndMap('model.videoCount', 'model.videos')
  .where('model.id = :id', { id: id })        
  .getOne();
Run Code Online (Sandbox Code Playgroud)