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")
方法.
相关文章