As mentioned in here, we can use the word cascade
when making a relation in migrations
but I wonder they didn't say anything about other actions when deleting
or updating
a foreign key
so I'm not sure if there is such thing or not:
$table->foreign('user_id')
->references('id')->on('users')
->onDelete('set null');
//->onDelete('set_null');
//->onDelete('setNull');
or the same thing about onUpdate
and about no action
just like the phpMyAdmin
thanks
ON DELETE CASCADE constraint is used in MySQL to delete the rows from the child table automatically, when the rows from the parent table are deleted.
How to change data type of column in laravel 9 migration ? Step 1 : Install doctrine/dbal package. Step 2 : Generate migration file. Step 3 : Open generated migration file and update.
You can do all the options mentioned in phpmyadmin
this way:
$table->...->onDelete('CASCADE');
$table->...->onDelete('SET NULL');
$table->...->onDelete('RESTRICT');
// do not call the onDelete() method if you want the RESTRICT option.
You have to make sure you set the foreign key field as nullable:
$table->...->unsigned()->nullable();
Referring to the source code:
`vendor/laravel/framework/src/Illuminate/Database/Schema/Grammars/Grammar.php` in the function compileForeign()
It just appends whatever you pass in to the table query.
if (! is_null($command->onDelete)) {
$sql .= " on delete {$command->onDelete}";
}
if (! is_null($command->onUpdate)) {
$sql .= " on update {$command->onUpdate}";
}
So, make sure you pass one of the following: "cascade", "no action", "restrict", or "set null"
NOTE: Do NOT use underscores in the actions like "set_null" and "no_action"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With