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:
- TypeORM: How to Execute Raw SQL Queries
- How to Use Subqueries in TypeORM
- TypeORM: How to Use Column Alias when Querying Data
- TypeORM: Counting Records in One-To-Many Relation
- TypeORM: Selecting Rows Between 2 Dates
- Pagination in TypeORM (Find Options & QueryBuilder)
You can also check out our database topic page for the latest tutorials and examples.