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

Rob*_*ore 7 typescript typeorm

我在 TypeORM 中有一个一对多关系,我想从关系的多方删除行,而不是通过将外键设置为 null(默认行为)来取消它们的链接,从而使它们成为孤立的。如何才能做到这一点?我看到了此功能的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[];
}
Run Code Online (Sandbox Code Playgroud)

Tob*_*ias 9

2021 年 1 月 12 日合并的另一个PR修复了这个问题。

此功能自 TypeORM 版本0.2.30起可用:

0.2.30 (2021-01-12)

特征

  • 关系:孤立行操作 (#7105) (efc2837)

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

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

  • 您好,在此示例中,这是否意味着如果您删除“business”表中的一行(此处由实体 BusinessGeolocation 表示),那么只有当该行位于“Business”类型的相关实体中时,才会删除该行。类型“Business”的相关实体没有“business”表中的任何其他行指向它?所以基本上现在我的理解是,如果我执行以下操作,它就会起作用:await BusinessGeolocation.remove(varOfTypeBusinessGeolocation); 我有相同的设置,减去 @childEntity() 开销,但它对我不起作用,相关的业务实体仍然存在...... (2认同)