Laravel - 使用数据在现有表上添加外键 [英] Laravel - add foreign key on existing table with data

查看:466
本文介绍了Laravel - 使用数据在现有表上添加外键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有现有的表对象与数据。现在我需要添加一个名为持有的新表,并添加一个从对象到持股表的关系。在迁移文件中,我输出:

  $ table-> foreign('hold_id') - > references(' ('持有') - > onDelete(NO ACTION); 

并在尝试迁移时得到此错误

  SQLSTATE [23000]:完整性约束违规:1452无法添加或更新
a子行:外键约束失败(`kolomnaoffice`.`#sql-f10_126`
CONSTRAINT`objects_holding_id_foreign` FOREIGN KEY(`holding_id`)
参考``持有`(`id`)ON DELETE NO ACTION)(SQL:alter table`objects`添加约束$ b $``objects_holding_id_foreign`外键(`hold_id`)引用`持有'
(`id`)on delete NO ACTION)

我有正确的数据库结构(两个InnoDB),字段存在并具有正确的类型(int)。唯一不同的是,表 objects 充满了数据,而表持有是新的和空的。 p>

解决方案

holding_id 列应该是 unsigned

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

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

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

change()



不需要定义 onDelete(NO ACTION)


I have existing table objects with data. Now I need to add new table named holdings and add a relation from objects to holdings table. In the migration file, I print this:

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

and get this error when trying to migrate

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)

I have correct database structure (both InnoDB), the fields exist and have correct type (int). The only thing different is that the table objects is filled with data, and table holdings is new and empty.

解决方案

holding_id column should be unsigned

create a new migration file and migrate it, migration code should be like this :

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

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

change() method for change structure of column

its not necessary to define onDelete("NO ACTION") too

这篇关于Laravel - 使用数据在现有表上添加外键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆