Search code examples
node.js-typeormtypeorm-datamapper

TypeORM ManyToMany with createsQueryBuilder


I have, three entities, services, accounts, and the union of the two, contasservices:

Services:

@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;
}

Accounts:

@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;

}

AccountsServices :

@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;

}

How do I run a createQueryBuilder in my repository and get the following json back: const query = 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
      }    
    ]
  }
]

Solution

  • Try this:

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