Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does onDelete('cascade') mean?

Tags:

php

laravel

Schema::table('posts', function (Blueprint $table) {     $table->integer('user_id')->unsigned();     $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade'); }); 

Does this mean that if I delete a post, the user will also be deleted or does it mean if I delete a user, all their posts will be deleted?

like image 454
code511788465541441 Avatar asked Mar 29 '17 13:03

code511788465541441


People also ask

What does onDelete Cascade do?

Use the ON DELETE CASCADE option to specify whether you want rows deleted in a child table when corresponding rows are deleted in the parent table. If you do not specify cascading deletes, the default behavior of the database server prevents you from deleting data in a table if other tables reference it.

What does Cascade mean in SQL?

Cascade in SQL is used to delete or update an entry from both the child and the parent table simultaneously. The keyword CASCADE is used as conjunction while writing the query of ON DELETE or ON UPDATE.

What is Cascade in Typeorm?

cascade: boolean | ("insert" | "update")[] - If set to true, the related object will be inserted and updated in the database. You can also specify an array of cascade options. onDelete: "RESTRICT"|"CASCADE"|"SET NULL" - specifies how foreign key should behave when referenced object is deleted.

What does cascade delete mean in SQL?

A foreign key with cascade delete means that if a record in the parent table is deleted, then the corresponding records in the child table will automatically be deleted. This is called a cascade delete in SQL Server.


1 Answers

Short answer is: in your case, if you deleted a user, all posts related to him will be deleted too.

onDelete('cascade'); simply adds ON DELETE CASCADE rule to your database which specifies that the child data gets deleted when the parent data is deleted.

Note: take care of the typo (double semicolon)

$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');

like image 169
M.Elwan Avatar answered Sep 21 '22 09:09

M.Elwan