Laravel - 无法解决完整性约束违规

问题描述 投票:1回答:2

我创建了一个新的迁移,以将列添加到现有表并将外键添加到现有表。

这是使用新列的迁移:

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

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

当我运行migrate命令时,我得到:

[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`))  

我怎么解决?

mysql laravel-5.2
2个回答
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
投票

我发生了同样的事情,但我解决了这个问题,在创建列时添加了一个默认值:

$table->integer( 'category_id' )->unsigned()->after( 'place_id' )->default(1);

确保表“categories”具有id = 1的记录。

© www.soinside.com 2019 - 2024. All rights reserved.