Search code examples
typescriptexpresstypeorm

How to auto delete the children if parent is removed or deleted?


I have the following entity. How can I auto delete the childCategories if the parent category is deleted using category repository's delete or remove?

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[];
}

Actually, I tried delete the category by id, the category is deleted but it's children data still remain in the database.


Solution

  • Please add an onDelete: 'CASCADE' to the parent relationship.

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

    References: