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:

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

export class Comment {
  id: number;

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

  body: string;

User entity:

// User entity
import {
} from 'typeorm';
import { Comment } from './Comment.entity';

export class User {
  id: number;

  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.

Notify of
Inline Feedbacks
View all comments

Related Articles