Cascade Delete in TypeORM

Updated: September 27, 2022 By: Snowball Post a comment

When working with a database, the cascade delete feature ensures that deleting a parent record will also remove the child records. For instance, we have a table that stores information about users and another table that stores comments. When a user is removed, all comments belonging to him/her will go away, too.

In TypeORM, we can enable cascade delete in relation by adding {onDelete:’CASCADE’} to the @ManyToOne decorator.

Comment entity:

// KindaCode.com Example
// Comment entity
import { Entity, Column, PrimaryGeneratedColumn, ManyToOne } from 'typeorm';
import { User } from './User.entity';

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

  @ManyToOne((type) => User, (user) => user.comments, { 
    onDelete: 'CASCADE' 
  })
  user: User;

  @Column()
  body: string;
}

User entity:

// KindaCode.com
// User entity
import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  OneToMany
} from 'typeorm';
import { Comment } from './Comment.entity';

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

  @Column()
  name: string;

  @OneToMany((type) => Comment, (comment) => comment.user)
  comments: Comment[];
}

From now on, whenever you delete a user, all related comments will be erased as well.

Further reading:

You can also check out our database topic page for the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles