laravel migration best way to add foreign key

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

    You should create a new migration file let's 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'); //
        });
    }  
    

    The run

     php artisan migrate
    

提交回复
热议问题