带有 createsQueryBuilder 的 TypeORM ManyToMany

TypeORM ManyToMany with createsQueryBuilder

我有,三个实体,服务,账户,以及两者的结合,contasservices:

服务:

@Entity({ name: 'services' })
export class ServiceEntity {

  @PrimaryGeneratedColumn()
  public id: number;

  @OneToMany(type => AccountServiceEntity, x => x.service)
  accountAndServices: AccountServiceEntity[];

  @Column({ nullable: false, length: 150 })
  public name: string;
}

帐户:

@Entity({ name: 'accounts' })
export class AccountEntity {

  @PrimaryGeneratedColumn()
  public id: number;

  @OneToMany(type => AccountServiceEntity, x => x.account)
  accountAndServices: AccountServiceEntity[];

  @Column({ nullable: false })
  public account_type: number;

}

账户服务:

@Entity({ name: 'accounts_services' })
export class AccountServiceEntity {

  @PrimaryGeneratedColumn()
  public id: number;

  @ManyToOne(() => ServiceEntity, x => x.accountAndServices, 
                         { primary: true, nullable: false })
  service: ServiceEntity;

  @ManyToOne(() => AccountEntity, x => x.accountAndServices, 
                         { primary: true, nullable: false })
  account: AccountEntity;

  @Column({ nullable: false })
  public date_initial: Date;

}

如何 运行 我的存储库中的 createQueryBuilder 并获得以下 json 返回: const 查询 = this.repository.createQueryBuilder("...")

[
  {
    "account_name": "Gladson",
    "serices": [
      {
        "description": "xxxx",
        "date_initial": "31/07/2021"  
        "value": 10,00
      },
      {
        "description": "yyy",
        "date_initial": "31/07/2021"  
        "value": 2,00
      }    
    ]
  }
]

试试这个:

const queryBuilder = repository.createQueryBuilder('Account')
queryBuilder
    .leftJoinAndSelect('Account.accountAndServices', 'accountAndServices')
    .leftJoinAndSelect('accountAndServices.service', 'service')
    .select(['Account.id', 'accountAndServices.id', 'service.description'])
await queryBuilder.getMany()