Laravel migration is the best way to add a foreign key

A simple question: I am new to Laravel. I have a migration file:

Schema::create('lists', function(Blueprint $table) { $table->increments('id'); $table->string('title', 255); $table->integer('user_id')->unsigned(); $table->foreign('user_id')->references('id')->on('users'); $table->timestamps(); }); 

I want to update it to add onDelete('cascade') .

What is the best way to do this?

+5
source share
4 answers

First, you must make the user_id field user_id index:

 $table->index('user_id'); 

After that, you can create a foreign key with an action on the cascade:

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

If you want to do this with a new migration, you first need to remove the index and foreign key and do everything from scratch.

In the down () function, you must do this, and then on up () do what I wrote above:

 $table->dropForeign('lists_user_id_foreign'); $table->dropIndex('lists_user_id_index'); $table->dropColumn('user_id'); 
+7
source

You must create a new migration file, say 'add_user_foreign_key.php'

 public function up() { Schema::table('lists', function(Blueprint $table) { $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('lists', function(Blueprint $table) { $table->dropForeign('user_id'); // }); } 

Launch

  php artisan migrate 
+2
source
 $table->integer('user_id')->unsigned(); $table->foreign('user_id')->references('id')->on('users'); 

In this example, we say that the user_id column refers to the id column in the users table. Be sure to first create a foreign key column! The column user_id is declared unsigned because it cannot have a negative value.

You can also specify parameters for the "on delete" and "on update" restrictions:

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

To remove a foreign key, you can use the dropForeign method. A similar naming convention is used for foreign keys that are used for other indexes:

 $table->dropForeign('posts_user_id_foreign'); 

If you're fairly new to Laravel and Eloquent , try Laravel From Scratch available on Laracasts. This is a great guide for beginners.

+1
source

If you want to add onDelete('cascade') , just release the indexes and create them again:

 public function up() { Schema::table('lists', function($table) { $table->dropForeign('lists_user_id_foreign'); $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade'); }); } public function down() { Schema::table('lists', function($table) { $table->dropForeign('lists_user_id_foreign'); $table->foreign('user_id')->references('id')->on('users'); }); } 
0
source

Source: https://habr.com/ru/post/1204968/


All Articles