Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel :: Best way to update a foreign key

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

like image 640
Yevgeniy Afanasyev Avatar asked Jul 18 '16 02:07

Yevgeniy Afanasyev


People also ask

How do you update a table that has a foreign key?

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.

Can we update foreign key column?

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.

Which method is used for update in laravel?

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.


2 Answers

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');     }); } 
like image 181
Borut Flis Avatar answered Oct 08 '22 12:10

Borut Flis


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

like image 43
Ricard Avatar answered Oct 08 '22 14:10

Ricard