乐闻世界logo
搜索文章和话题

How to auto-remove orphaned rows in TypeORM?

1个答案

1

Introduction

In TypeORM, handling the automatic deletion of orphaned rows typically involves ensuring that when an entity is deleted, all related entities are automatically removed to prevent orphaned data in the database.

1. Using Cascade Delete

In TypeORM, you can enable cascade delete by setting cascade: ['remove'] when defining entity relationships. This ensures that when an entity is deleted, all related entities are automatically deleted.

Example:

Suppose there are two entities, User and Photo, where User can have multiple Photo instances:

typescript
@Entity() export class User { @PrimaryGeneratedColumn() id: number; @OneToMany(() => Photo, photo => photo.user, { cascade: ['remove'] }) photos: Photo[]; } @Entity() export class Photo { @PrimaryGeneratedColumn() id: number; @ManyToOne(() => User, user => user.photos) user: User; }

In this example, deleting a User entity will automatically delete all associated Photo entities.

2. Using Foreign Key Constraints in the Database

Another approach is to set up foreign key constraints at the database level to ensure that when a record is deleted, all referencing rows are also deleted. This is typically implemented during database table creation using SQL statements.

In TypeORM, you can achieve this by setting onDelete: 'CASCADE' when defining entity relationships.

Example:

typescript
@Entity() export class Photo { @PrimaryGeneratedColumn() id: number; @ManyToOne(() => User, user => user.photos, { onDelete: 'CASCADE' }) user: User; }

In this example, deleting a User entity will automatically delete all associated Photo entities because onDelete: 'CASCADE' is set.

Summary

When choosing between cascade delete and foreign key constraints, consider the application's specific requirements and database performance. Cascade delete offers greater flexibility and ease of use as it is managed by the ORM framework. Foreign key constraints, on the other hand, are more dependent on the database implementation and are typically more performant, but may require adjustments when working across different databases.

2024年6月29日 12:07 回复

你的答案