Laravel - add foreign key on existing table with data(Laravel - 在现有表上添加外键和数据)
问题描述
我有现有的表 objects
与数据.现在我需要添加名为 holdings
的新表,并将对象之间的关系添加到 holdings
表.在迁移文件中,我打印了这个:
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)
我有正确的数据库结构(两个 InnoDB),字段存在并且具有正确的类型(int).唯一不同的是,objects
表是数据,而holdings
表是新的空的.
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
列应该是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()
方法改变现有列的结构.
The change()
method is called to change the structure of existing column.
不需要调用onDelete("NO ACTION")
方法.
这篇关于Laravel - 在现有表上添加外键和数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Laravel - 在现有表上添加外键和数据


基础教程推荐
- MySQL 5.7参照时间戳生成日期列 2022-01-01
- 带更新的 sqlite CTE 2022-01-01
- CHECKSUM 和 CHECKSUM_AGG:算法是什么? 2021-01-01
- 带有WHERE子句的LAG()函数 2022-01-01
- ORA-01830:日期格式图片在转换整个输入字符串之前结束/选择日期查询的总和 2021-01-01
- 如何在 CakePHP 3 中实现 INSERT ON DUPLICATE KEY UPDATE aka upsert? 2021-01-01
- while 在触发器内循环以遍历 sql 中表的所有列 2022-01-01
- MySQL根据从其他列分组的值,对两列之间的值进行求和 2022-01-01
- 从字符串 TSQL 中获取数字 2021-01-01
- 使用 VBS 和注册表来确定安装了哪个版本和 32 位 2021-01-01