2016-01-04 49 views
1

我已經創建了一個新的遷移,以將列添加到現有表並向現有表中添加外鍵。Laravel - 無法解決完整性約束違規

這是新列遷移:

Schema::table('events', function (Blueprint $table) { 

    $table->integer('category_id')->unsigned()->after('place_id'); 
    $table->foreign('category_id')->references('id')->on('categories'); 
}); 

當我運行遷移命令我得到:

[Illuminate\Database\QueryException]                                   
    SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`meetmount`.`#sql-3c8_424`, CONSTRAINT `events_catego 
    ry_id_foreign` FOREIGN KEY (`category_id`) REFERENCES `categories` (`id`)) (SQL: alter table `events` add constraint events_category_id_foreign foreign key (`category_id`) r 
    eferences `categories` (`id`)) 

[PDOException]                                         
    SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`meetmount`.`#sql-3c8_424`, CONSTRAINT `events_catego 
    ry_id_foreign` FOREIGN KEY (`category_id`) REFERENCES `categories` (`id`)) 

我該如何解決?

回答

1

錯誤的原因可能是以下幾點:

父表categories和/或子表events已經在他們的記錄。當你想引用父表的特定列(id)時,MySQL將期望子表具有存在於父表中的值,因此完整性約束違規

一個可能的解決方案(如果家長不爲空)是在events表中添加默認值的外鍵列:

$table->integer('category_id')->unsigned()->after('place_id'); 
$table->foreign('category_id')->references('id')->on('categories')->default(1); 
+0

謝謝,這個問題是不是空的父表 –

相關問題