【问题标题】:Removing many2many entity in typeorm with cascade使用级联删除 typeorm 中的 many2many 实体
【发布时间】:2020-09-07 04:28:38
【问题描述】:

我有一个名为 Entry 的实体,它与另一个名为 Image 的实体关联为 Many2Many。

EntryImage 关系如下所示:

@Entity('entry')
export class EntryEntity extends BaseEntity implements IDeserializable<EntryEntity> {
    @ManyToMany(type => ImageEntity, image => image.entries, { onDelete: 'CASCADE', cascade: true })
    @JoinTable()
    images: ImageEntity[];
}

Image 实体类:

@Entity('image')
export class ImageEntity extends BaseEntity implements IDeserializable<ImageEntity> {
    @ManyToMany(type => EntryEntity, entry => entry.images)
    entries: EntryEntity[];
}

我用来删除条目的方法:

    public async delete(entryId: number): Promise<void> {
      const queryRunner = this.connection.createQueryRunner();
      await queryRunner.connect();
      await queryRunner.startTransaction();
      try {
        await queryRunner.manager.getRepository(EntryEntity)
                                 .createQueryBuilder('entry')
                                 .delete()
                                 .from(EntryEntity)
                                 .where('entry.id = :entryId', { entryId })
                                 .execute();
        await queryRunner.commitTransaction();
      } catch (err) {
        await queryRunner.rollbackTransaction();
      } finally {
        await queryRunner.release();
      }
    }

预期行为:

如果我删除了某个条目,那么它的所有图像也应该被删除。

实际行为:

条目从其表中删除,它也从entry_images_image 表中删除 但与此条目关联的图像仍然存在(它们仍然存在于image 表中)。

我对TypeOrm不是很熟悉,为什么会这样?非常感谢您的帮助。

【问题讨论】:

    标签: node.js nestjs typeorm


    【解决方案1】:

    级联的作用是删除双方的关系,而不是实体本身。所以在你的情况下,你只会收到没有关系的图像,正如你所提到的。

    这样看:假设您有多个条目的多个图像,所有图像都相互连接。如果你删除一个条目,你真的希望图像实体被完全删除吗?因为在这种情况下,您将删除很多尚未删除的数据。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-17
      • 2013-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-17
      • 2014-12-20
      相关资源
      最近更新 更多