SQLSTATE [23000]:完整性约束违规:1217

问题描述:

在我的项目中肌酸多次迁移后,我想回滚更新一些东西,但突然间,当我试图删除projects表时,出现此错误。我仔细检查了外键限制,但我找不到错误。SQLSTATE [23000]:完整性约束违规:1217

[Illuminate\Database\QueryException]           
    SQLSTATE[23000]: Integrity constraint violation: 1217 Cannot delete or upda 
    te a parent row: a foreign key constraint fails (SQL: drop table `projects` 
)                                       
    [PDOException]                
    SQLSTATE[23000]: Integrity constraint violation: 1217 Cannot delete or upda 
    te a parent row: a foreign key constraint fails 

这里是我的迁移: 1.创建表的用户:

public function up() 
    { 
     Schema::create('users', function(Blueprint $table) 
     { 
      $table->increments('id'); 
      $table->string('first_name'); 
      $table->string('last_name'); 
      $table->string('email', 50)->unique(); 
      $table->string('password', 60); 
      $table->string('password_temp', 60); 
      $table->string('code', 60); 
      $table->boolean('active'); 
      $table->string('remember_token', 100); 
      $table->timestamps(); 
     }); 
    } 
    public function down() 
    { 
     Schema::drop('users'); 
    } 

2.创建客户表:

public function up() 
    { 
     Schema::create('clients', function(Blueprint $table) 
     { 
      $table->increments('id'); 
      $table->integer('user_id')->unsigned()->index()->nullable(); 
      $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade'); 
      $table->timestamps(); 
     }); 
    } 
    public function down() 
    { 
     Schema::drop('clients'); 
    } 

3.创建项目表:

public function up() 
    { 
     Schema::create('projects', function(Blueprint $table) 
     { 
      $table->increments('id'); 
      $table->string('name'); 
      $table->integer('status'); 
      $table->integer('client_id')->unsigned()->index()->nullable(); 
      $table->foreign('client_id')->references('id')->on('users')->onDelete('cascade');  
      $table->timestamps(); 
     }); 
    } 
    public function down() 
    { 
     Schema::drop('projects'); 
    } 

在l人为迁移,我可能会犯的错误是什么?!迁移时我不会遇到任何问题,但只有在回滚才能添加任何更改时才会显示。

任何想法为什么发生这种情况?

如果只有3上面提到的表,有一个在您的迁移没有问题,因为我已经尝试过自己与

php artisan migrate 

创建表和

php artisan migrate:rollback 

回滚。

我知道的一件事是Laravel将假设基于迁移文件时间戳的迁移序列。

因此,我十分肯定的是,有一个外键引用尚未下降为错误讯息的projects表另一个表(SQL:DROP TABLE projects

尝试使用php artisan tinker和那么Schema::drop('some_table_name');其中some_table_name是表的参考projects表,然后再删除projects表。

+3

这不是问题的答案。 – 2015-04-19 17:19:02

在down函数中使用它。

public function down() 
{ 
    DB::statement('SET FOREIGN_KEY_CHECKS = 0'); 
    Schema::dropIfExists('tableName'); 
    DB::statement('SET FOREIGN_KEY_CHECKS = 1'); 
} 

当你使用你的表的外键,你需要你放下你的表之前删除使用dropForeign方法的,否则你会碰到目前你所得到的完整性约束的问题。

public function down() 
{ 
    Schema::table('projects', function(Blueprint $table) { 
     $table->dropForeign('projects_client_id_foreign'); 
    }); 

    Schema::drop('projects'); 
} 

此问题通常是通过编辑/添加到现有迁移中创建的。 在处理外键时创建新的迁移文件或准备好转储/删除整个数据库并刷新。