Select 仅在 TypeORM 中具有相关多对多键的实体

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

对于多对多关系,是否可以自动 select只关联外键,而不select整个关联对象?无需使用查询构建器等额外逻辑来显式加入关系 table.

假设我有 BankCountry 实体,具有多对多关系(一些银行在多个国家/地区运营)。这是我想要实现的目标:

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

对于一对多关系,可以在关系上使用 @JoinColumn(name: 'countryId'),然后使用 @Column() countryId: number

对于多对多关系是否可能存在类似的情况,select 只是实体中的外键,但没有 select 整个相关国家,也没有使用查询构建器?

您可以使用 @RelationId 来做到这一点,然后预先加载国家/地区 ID,因此您不需要任何额外的查询:

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

    @RelationId('countries')
    countryIds?: number[];