Search code examples
typeorm

Select entity with related many-to-many keys only in TypeORM


With a many-to-many relation, is it possible to automatically select just the related foreign keys, without selecting the whole related objects? Without using additional logic like query builders to explicitly join the relation table.

Suppose I have Bank and Country entities, with a many-to-many relation (some banks operate in more than one country). Here's what I'd want to achieve:

@Entity()
export class Country {
  @PrimaryGeneratedColumn()
  id!: number;
  // ... other columns
}

@Entity
export class Bank {
  @PrimaryGeneratedColumn()
  id!: number;

  // ... other columns

  @ManyToMany(_type => Country)
  @JoinTable()
  countries?: Country[];

  // TODO: how to achieve this without tricks?
  countryIds?: number[];
}

With a one-to-many relation, it was possible to use @JoinColumn(name: 'countryId') on the relation, and then @Column() countryId: number.

Is something similar possible for many-to-many relations, to select just the foreign keys into the entity, but without selecting the whole related countries, and without using a query builder?


Solution

  • You can do that by using @RelationId, the country ids are then eager-loaded, so you don't need any additional queries:

    @Entity()
     export class Bank { 
        @PrimaryGeneratedColumn() 
        id!: number; 
        @ManyToMany(_type => Country) 
        @JoinTable() 
        countries?: Country[];
    
        @RelationId('countries')
        countryIds?: number[];