laravel migration best way to add foreign key

后端 未结 10 1107
梦毁少年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:54

    Firstly you have to make your user_id field an index:

    $table->index('user_id');
    

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

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

    If you want to do that with a new migration, you have to remove the index and foreign key firstly and do everything from scratch.

    On down() function you have to do this and then on up() do what I've wrote above:

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

提交回复
热议问题