Dropping foreign keys in Laravel migration

后端 未结 3 2387
花落未央
花落未央 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.

    0 讨论(0)
  • 2021-02-20 15:43

    In all of the >4.0 versions of Laravel, it allows placing column names into an array, which it will then resolve on its own. I tried to find accompanying docs, but they seem to have left it out.

    In your update migration, try this:

    Schema::table('role_user', function (Blueprint $table) {
      $table->dropForeign(['user_id']);
      $table->dropForeign(['role_id']);
    });
    
    0 讨论(0)
  • 2021-02-20 15:56

    I have modified your code below.

    Add the onDelete() and onUpdate() to your code.

    public function up() 
    {
        Schema::table('role_user',function(Blueprint $table) {
            $table->foreign('user_id')->references('id')->on('users')->onDelete('CASCADE')->onUpdate('CASCADE');
            $table->foreign('role_id')->references('id')->on('roles')->onDelete('CASCADE')->onUpdate('CASCADE');
        });
    }
    

    public function down() {
        Schema::table('role_user', function (Blueprint $table) {
            $table->dropForeign(['user_id']);
            $table->dropForeign(['role_id']);
        });
    }
    
    0 讨论(0)
提交回复
热议问题