laravel migration best way to add foreign key

后端 未结 10 1069
梦毁少年i
梦毁少年i 2020-12-09 09:19

Simple question: I\'m new to Laravel. I have this migration file:

Schema::create(\'lists\', function(Blueprint $table) {
    $table->increments(\'id\'); 
         


        
10条回答
  •  独厮守ぢ
    2020-12-09 09:50

    $table->integer('user_id')->unsigned();
    $table->foreign('user_id')->references('id')->on('users');
    

    In this example, we are stating that the user_id column references the id column on the users table. Make sure to create the foreign key column first! The user_id column is declared unsigned because it cannot have negative value.

    You may also specify options for the "on delete" and "on update" actions of the constraint:

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

    To drop a foreign key, you may use the dropForeign method. A similar naming convention is used for foreign keys as is used for other indexes:

    $table->dropForeign('posts_user_id_foreign');
    

    If you are fairly new to Laravel and Eloquent, try out the Laravel From Scratch series available on laracasts. It is a great guide for beginners.

提交回复
热议问题