2017-05-25 122 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']); 
    }); 
}