2017-05-25 102 views
0

我在我的laravel應用程序中刪除外鍵時遇到問題。問題是,當我試圖回滾遷移:在Laravel遷移中刪除外鍵

php artisan migrate:rollback 

我不知道爲什麼我在控制檯有一個錯誤:

[Illuminate\Database\QueryException] 
    SQLSTATE[42000]: Syntax error or access violation: 1091 Can't DROP 'role_user_user_id_foreign'; check that column/k 
    ey exists (SQL: alter table `role_user` drop foreign key `role_user_user_id_foreign`) 

    [Doctrine\DBAL\Driver\PDOException] 
    SQLSTATE[42000]: Syntax error or access violation: 1091 Can't DROP 'role_user_user_id_foreign'; check that column/k 
    ey exists 

    [PDOException] 
    SQLSTATE[42000]: Syntax error or access violation: 1091 Can't DROP 'role_user_user_id_foreign'; check that column/k 
    ey exists 

在下面,我shwoing我的移民類:

class UpdateRoleUserTable extends Migration 
{ 
    /** 
    * Run the migrations. 
    * 
    * @return void 
    */ 
    public function up() 
    { 
     schema::table('role_user',function(Blueprint $table){ 


      $table->foreign('user_id')->references('id')->on('users'); 
      $table->foreign('role_id')->references('id')->on('roles'); 

     }); 
    } 

    /** 
    * Reverse the migrations. 
    * 
    * @return void 
    */ 
    public function down() 
    { 
     Schema::table('role_user', function (Blueprint $table) { 
     $table->dropForeign('role_user_user_id_foreign'); 
     $table->dropForeign('role_user_role_id_foreign'); 

    }); 
    } 
} 

我在數據庫表已被遷移類創建:

class CreateRoleUserTable extends Migration 
{ 
    /** 
    * Run the migrations. 
    * 
    * @return void 
    */ 
    public function up() 
    { 
     Schema::create('role_user', function (Blueprint $table) { 

      $table->increments('id'); 
      $table->integer('user_id')->unsigned(); 
      $table->integer('role_id')->unsigned(); 

     }); 
    } 

    /** 
    * Reverse the migrations. 
    * 
    * @return void 
    */ 
    public function down() 
    { 
     Schema::dropIfExists('role_user'); 
    } 
} 

回答

2

在Laravel的所有> 4.0版本中,它允許將列名放入數組中,然後它將自行解析。我試圖找到隨附的文檔,但他們似乎已將其排除在外。

在你的更新遷移,試試這個:

Schema::table('role_user', function (Blueprint $table) { 
    $table->dropForeign(['user_id']); 
    $table->dropForeign(['role_id']); 
}); 
0

我在下面的代碼修改方式。

onDelete()onUpdate()添加到您的代碼中。

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']); 
    }); 
}