我有以下实体.如果使用类别存储库的删除或移除删除父类别,我如何自动删除子类别?

import { UserEntity } from '@entities/user.entity';
import { Entity, Column, ManyToOne, PrimaryGeneratedColumn, Relation, OneToMany } from 'typeorm';

@Entity()
export class CategoryEntity {
  @PrimaryGeneratedColumn()
  id: number;

  @Column({ nullable: false, unique: true })
  name: string;

  @Column({ nullable: false })
  icon: string;

  @ManyToOne(Type => UserEntity, user => user.categories)
  user: Relation<UserEntity>;

  @ManyToOne(type => CategoryEntity, category => category.childCategories, {
    createForeignKeyConstraints: false,
  })
  parentCategory: CategoryEntity;

  @OneToMany(type => CategoryEntity, category => category.parentCategory)
  childCategories: CategoryEntity[];
}

实际上,我试着按id删除类别,类别被删除了,但它的子数据仍然保留在数据库中.

推荐答案

请在父关系上加上onDelete: 'CASCADE'.

  @ManyToOne(type => CategoryEntity, category => category.childCategories, {
    createForeignKeyConstraints: false,
    onDelete: 'CASCADE',
  })
  parentCategory: CategoryEntity;

参考资料:

Typescript相关问答推荐

为什么在将条件返回类型的字符串赋给数字时没有类型错误?

如何根据参数的值缩小函数内的签名范围?

React Hook中基于动态收件箱定义和断言回报类型

等待的R没有用响应对象展开到R

使用前的组件渲染状态更新

ReturnType此索引方法与点表示法之间的差异

TypeScript:在作为参数传递给另一个函数的记录中对函数的参数实现类型约束

如何将CSV/TXT文件导入到服务中?

路由链接始终返回到

Angular文件上传到Spring Boot失败,多部分边界拒绝

try 呈现应用程序获取-错误:动作必须是普通对象.使用自定义中间件进行MySQL操作

有没有可能创建一种类型,强制在TypeScrip中返回`tyPeof`语句?

我不明白使用打字脚本在模板中展开参考

在抽象类构造函数中获取子类型

为什么类型脚本使用接口来声明函数?他的目的是什么.

推断集合访问器类型

在打印脚本中将对象类型转换为数组

在Vite中将SVG导入为ReactComponent-不明确的间接导出:ReactComponent

通过函数传递确切的类型,但验证额外的字段

确保财产存在