Ale*_*kov 7 mysql migration foreign-keys laravel laravel-5.4
我有现有的objects数据表.现在我需要holdings添加一个名为的新表,并添加从对象到holdings表的关系.在迁移文件中,我打印出来:
$table->foreign('holding_id')->references('id')->on('holdings')->onDelete("NO ACTION");
Run Code Online (Sandbox Code Playgroud)
尝试迁移时出现此错误
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)
Run Code Online (Sandbox Code Playgroud)
我有正确的数据库结构(都是InnoDB),字段存在并且具有正确的类型(int).唯一不同的是表objects填充了数据,表holdings是新的和空的.
Moh*_*d b 11
该holding_id列应该是unsigned
创建一个新的迁移文件并进行迁移,迁移代码应如下所示:
Schema::table('objects', function (Blueprint $table) {
$table->integer('holding_id')->unsigned()->change();
$table->foreign('holding_id')->references('id')->on('holdings');
});
Run Code Online (Sandbox Code Playgroud)
change()调用该方法以更改现有列的结构.
没有必要调用onDelete("NO ACTION")方法.
谢谢穆罕默德,但这个解决方案对我不起作用,Laravel 5.4而且这里有不同的情况,我的另一个表已经存在,我发现的可能对某些人有所帮助。
Schema::table('objects', function (Blueprint $table) {
$table->integer('holding_id')->unsigned()->index()->nullable();
$table->foreign('holding_id')->references('id')->on('holdings');
});
Run Code Online (Sandbox Code Playgroud)
与index()和nullable()它做的伎俩。
编辑
不需要index()它只需要nullable()
| 归档时间: |
|
| 查看次数: |
10296 次 |
| 最近记录: |