如何自动删除 TypeORM 中的孤立行?

How to auto-remove orphaned rows in TypeORM?

我在 TypeORM 中有一个一对多关系,我想从关系的多边删除行,而不是通过将它们的外键设置为 null(默认行为)来取消链接,让它们成为孤立的.如何才能做到这一点?我看到此功能的 a PR,但被拒绝了。有解决方法或其他方法吗?这是我的代码的简化版本,以提供一些上下文。

@Entity()
@TableInheritance({ column: { name: 'type', type: 'text' } })
export default class Geolocation {
  @PrimaryGeneratedColumn()
  id!: number;

  @IsGeoJSONPoint
  @Column('geography')
  point!: Point;
}


@ChildEntity('offer')
export default class OfferGeolocation extends Geolocation {
  @ManyToOne(type => Offer, offer => offer.geolocations, { onDelete: 'CASCADE' })
  offer!: Offer;
}


@ChildEntity('business')
export default class BusinessGeolocation extends Geolocation {
  @ManyToOne(type => Business, business => business.geolocations, { onDelete: 'CASCADE' })
  business!: Business;
}


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

  // I would like to remove orphaned business geolocations
  @OneToMany(type => BusinessGeolocation, businessGeolocation => businessGeolocation.business, { cascade: true })
  geolocations!: BusinessGeolocation[];
}


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

  // I would like to remove orphaned offer geolocations as well
  @OneToMany(type => OfferGeolocation, offerGeolocation => offerGeolocation.offer, { cascade: true })
  geolocations!: OfferGeolocation[];
}

另一个 PR 已于 2021 年 1 月 12 日合并,解决了这个问题。

此功能自 TypeORM 版本 0.2.30:

起可用

0.2.30 (2021-01-12)

Features

  • relations: Orphaned row action (#7105) (efc2837)

你应该能够通过以下方式实现你想要的:

@ChildEntity('business')
export default class BusinessGeolocation extends Geolocation {
  @ManyToOne(
    type => Business, business => business.geolocations, {
      onDelete: 'CASCADE',
      orphanedRowAction: "delete" // NEW
    })
  business!: Business;
}