2015-01-21 150 views
1

在我的項目中肌酸多次遷移後,我想回滾更新一些東西,但突然間,當我試圖刪除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

如果只有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

3

在down函數中使用它。

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

當你使用你的表的外鍵,你需要你放下你的表之前刪除使用dropForeign方法的,否則你會碰到目前你所得到的完整性約束的問題。

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

    Schema::drop('projects'); 
} 
1

此問題通常是通過編輯/添加到現有遷移中創建的。 在處理外鍵時創建新的遷移文件或準備好轉儲/刪除整個數據庫並刷新。

相關問題