【问题标题】:Select entity with related many-to-many keys only in TypeORM仅在 TypeORM 中选择具有相关多对多键的实体
【发布时间】:2019-09-26 20:20:27
【问题描述】:

对于多对多关系,是否可以自动只选择相关的外键,而不选择整个相关的对象?无需使用查询构建器等额外逻辑来显式连接关系表。

假设我有 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

对于多对多关系是否有类似的可能,只选择实体的外键,但不选择整个相关国家,也不使用查询构建器?

【问题讨论】:

    标签: typeorm


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2019-04-24
      • 2019-03-06
      • 2016-04-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-25
      • 2018-10-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多