In TypeORM, cascading operations involving related entities are enabled when an action such as persist, update or remove is done on the parent entity. This function greatly reduces the complexity of operations in the database since relations are taken care of.
Cascading operations perform actions like INSERT, REMOVE, or UPDATE on a certain entity which and scope these actions to include the child entity as well. This ensures data consistency and mitigation of redundant calls to the database.
Insert Cascade (cascade: true)
Update Cascade (cascade: true)
Delete Cascade: (onDelete: 'CASCADE')
Soft Remove Cascade (onDelete: 'SET NULL')
1. One-to-One Relation with Cascading
@Entity()
class Profile {
@PrimaryGeneratedColumn()
id: number;
@Column()
bio: string;
}
@Entity()
class User {
@PrimaryGeneratedColumn()
id: number;
@Column()
name: string;
@OneToOne(() => Profile, { cascade: true })
@JoinColumn()
profile: Profile;
}
Saving the User entity will also save the associated Profile entity.
2. The Cascade Version of One-to-Many Relationships
@Entity()
class Post {
@PrimaryGeneratedColumn()
id: number;
@Column()
title: string;
}
@Entity()
class User {
@PrimaryGeneratedColumn()
id: number;
@Column()
name: string;
@OneToMany(() => Post, (post) => post.user, { cascade: true })
posts: Post[];
}
Every time a User entity is saved, the Post entities within the posts array will also be automatically saved - assuming they have been added or updated.
3. The Cascade Version of Many-to-Many Relationships
@Entity()
class Student {
@PrimaryGeneratedColumn()
id: number;
@Column()
name: string;
@ManyToMany(() => Course, (course) => course.students, { cascade: true })
@JoinTable()
courses: Course[];
}
@Entity()
class Course {
@PrimaryGeneratedColumn()
id: number;
@Column()
title: string;
@ManyToMany(() => Student, (student) => student.courses)
students: Student[];
}
Updating the courses within the Student will also update the Course entity.
Queries that filter by indexed composite columns are the ones that benefit the most.
const users = await userRepository.find({ where: { firstName: 'John', lastName: 'Doe' } });
The database will utilize the composite index to return results with great speed, as it has the index.
Suppose cascading is not preferred, the decorator can easily be set to ignore it:
@OneToMany(() => Post, (post) => post.user, { cascade: false })
posts: Post[];
Cascading operations in TypeORM are great for maintaining the relations between various entities and data integrity, but comes with the trade-off of possibly causing unwanted deletion or modification of data.
Ready to transform your business with our technology solutions? Contact Us today to Leverage Our NodeJS Expertise.