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

Laravel - add foreign key on existing table with data(Laravel - 在现有表上添加外键和数据)
本文介绍了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 - 在现有表上添加外键和数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Hibernate reactive No Vert.x context active in aws rds(AWS RDS中的休眠反应性非Vert.x上下文处于活动状态)
Bulk insert with mysql2 and NodeJs throws 500(使用mysql2和NodeJS的大容量插入抛出500)
Flask + PyMySQL giving error no attribute #39;settimeout#39;(FlASK+PyMySQL给出错误,没有属性#39;setTimeout#39;)
auto_increment column for a group of rows?(一组行的AUTO_INCREMENT列?)
Sort by ID DESC(按ID代码排序)
SQL/MySQL: split a quantity value into multiple rows by date(SQL/MySQL:按日期将数量值拆分为多行)