Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeORM cascade option: cascade, onDelete, onUpdate

Do cascade options in TypeORM overlap or do they have a completely different purpose? Their description in the documentation is very scarce and partly missing, or I couldn't find it.

IOW, do the following options

{ cascade: "update" } = { onUpdate: 'CASCADE' }

{ cascade: "remove" } = { onDelete: 'CASCADE' }

have the same effect?

Or the cascade option is only for the TypeORM use while onUpdate and onDelete are only for the DB schema (created by migration)?

like image 614
Sergei Avatar asked Mar 11 '19 08:03

Sergei


People also ask

How do I use cascade in Typeorm?

The cascade option can be set as a boolean or an array of cascade options ("insert" | "update" | "remove" | "soft-remove" | "recover")[] . It will default to false , meaning no cascades. Setting cascade: true will enable full cascades. You can also specify options by providing an array.

What is onDelete (' cascade ') in laravel?

The onDelete('cascade') means that when the row is deleted, it will delete all it's references and attached data too. For example if you have a User which has a Post and you set onDelete('cascade') on the user, then when the user deletes his account, all posts will be deleted as well.


2 Answers

This is my conclusion of looking into it:

The cascade option does not affect the database column constraints, and I believe is used by TypeORM only in evaluating how to save entity relations to the database. We can define entities like this:

@Entity() class Book extends BaseEntity {     @ManyToOne(() => Author, (author) => author.books, {         onDelete: 'CASCADE',     })     public author?: Author }  @Entity() class Author extends BaseEntity {     @OneToMany(() => Book, (book) => book.author, {         cascade: true,     })     public books: Book[]; } 

onDelete sets the authorId foreign key to CASCADE onDelete on Book. This means that when the author is deleted, the book is also deleted.

Setting cascade: true on Author tells TypeORM that if a new book is appended on an author and the author is saved, the new book should also be saved to the database. Like this:

const author = await Author.findOne({ id: '123' }); author.books.push(new Book(...)); await author.save(); 

If cascade is not set on Book, the new book will not be saved to the database.

like image 71
nomadoda Avatar answered Sep 21 '22 17:09

nomadoda


onDelete: 'CASCADE isn't supported in OneToMany relations yet. More context here: https://github.com/typeorm/typeorm/issues/1913

like image 24
jstnno Avatar answered Sep 18 '22 17:09

jstnno