Dropping foreign keys in Laravel migration

后端 未结 3 2485
花落未央
花落未央 2021-02-20 14:58

I have a problem with dropping some foreign keys from my Laravel application. The problem is when I am trying to rollback the migration:

php artisan migrate:roll         


        
3条回答
  •  醉酒成梦
    2021-02-20 15:38

    I just had this issue and the problem was due to the fact that $table->dropForeign([column_name]); drops the index and not the column itself. The solution is in the down function drop the index in one block and then drop the actual column in a separate block. They have to be dropped in separate blocks because of something to do with not being able to drop the key in the same connection as where the column is being dropped.

    So the down function should look like this:

    public function down() {
        // drop the keys
        Schema::table('role_user', function (Blueprint $table) {
            $table->dropForeign(['user_id']);
            $table->dropForeign(['role_id']);
        });
    
       // drop the actual columns
       Schema::table('role_user', function (Blueprint $table) {
            $table->dropColumn('user_id');
            $table->dropColumn('role_id');
    
        });
    }
    

    now you can run php artisan migrate to run the up function and php artisan migrate:rollback to run the down command and the error no longer shows.

提交回复
热议问题