I have this migration file
Schema::create('table_one', function(Blueprint $table) { $table->increments('id'); $table->string('name'); $table->integer('table_two_id')->unsigned(); $table->foreign('table_two_id')->references('id')->on('table_two'); $table->timestamps(); });
and I want to update to make it ->onDelete('cascade');
$table->foreign('table_two_id')->references('id')->on('table_two')->onDelete('cascade');
What is the best way to do this?
Is there something like ->change();
Thanks
Login to the SQL Server using SQL Server Management Studio, Navigate to the Keys folder in the child table. Right click on the Keys folder and select New Foreign Key. Edit table and columns specification by clicking … as shown in the below image. Select the parent table and the primary key column in the parent table.
The FOREIGN KEY Constraint is a column or list of columns which points to the PRIMARY KEY of another table. you cannot simply update either child or parent table information in a Foreign Key relationship and that's the the purpose of it. If you want to update them, you have to enable, Update CASCADE on Parent table.
We can update the records using the DB facade with update method. The syntax of update method is as shown in the following table. Run an update statement against the database.
Drop the foreign key then add it again and run migrate.
public function up() { Schema::table('table_one', function (Blueprint $table) { $table->dropForeign(['table_two_id']); $table->foreign('table_two_id') ->references('id') ->on('table_two') ->onDelete('cascade'); }); }
Christopher K. is right, at the Laravel docs says:
To drop a foreign key, you may use the dropForeign method. Foreign key constraints use the same naming convention as indexes. So, we will concatenate the table name and the columns in the constraint then suffix the name with "_foreign":
$table->dropForeign('posts_user_id_foreign');
Or, you may pass an array value which will automatically use the conventional constraint name when dropping:
$table->dropForeign(['user_id']);
https://laravel.com/docs/5.7/migrations#foreign-key-constraints
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