Laravel - 使用数据在现有表上添加外键

问题描述:

我有现有的表objects数据。现在我需要添加一个名为holdings的新表,并添加一个从对象到holdings表的关系。在迁移文件,我打印:Laravel - 使用数据在现有表上添加外键

$table->foreign('holding_id')->references('id')->on('holdings')->onDelete("NO ACTION"); 

,并得到这个错误试图迁移

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update 
a child row: a foreign key constraint fails (`kolomnaoffice`.`#sql-f10_126` 
CONSTRAINT `objects_holding_id_foreign` FOREIGN KEY (`holding_id`) 
REFERENCES `holdings` (`id`) ON DELETE NO ACTION) (SQL: alter table `objects` add constraint 
`objects_holding_id_foreign` foreign key (`holding_id`) references `holdings` 
(`id`) on delete NO ACTION) 

我有正确的数据库结构(包括InnoDB的)时,该领域存在并有正确的类型(INT )。唯一不同的是表objects填充了数据,表holdings是新的和空的。

+0

试着让它可以列为空 –

holding_id列应该是unsigned

创建一个新的迁移文件,并进行迁移,迁移代码应该是这样的:

Schema::table('objects', function (Blueprint $table) { 
    $table->integer('holding_id')->unsigned()->change(); 

    $table->foreign('holding_id')->references('id')->on('holdings'); 
}); 

change()改变柱子结构的方法

其无需定义onDelete("NO ACTION")

+0

谢谢,它对我有用! –

要添加外键,首先确保您的列标记为无符号。

你行之前只需添加一行:

$table->integer('holding_id')->unsigned(); 
$table->foreign('holding_id')->references('id')->on('holdings')->onDelete("NO ACTION");