Laravel - 用数据在现有表上添加外键
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44744733/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel - add foreign key on existing table with data
提问by Alexander Guskov
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:
我有现有的objects
数据表。现在我需要添加命名的新表holdings
并添加从对象到holdings
表的关系。在迁移文件中,我打印了这个:
$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.
我有正确的数据库结构(都是 InnoDB),字段存在并且具有正确的类型(int)。唯一不同的是表objects
中填满了数据,而表holdings
是新的并且是空的。
回答by Mohammad b
The holding_id
column should be unsigned
该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');
});
The change()
method is called to change the structure of existing column.
change()
调用该方法来更改现有列的结构。
It's not necessary to call onDelete("NO ACTION")
method.
没有必要调用onDelete("NO ACTION")
方法。
回答by Yousef Altaf
Thanks Mohammad but this solution didn't work for me as I am Laravel 5.4
and have different case here that my other table is already exists, Here what I found may it help some one.
谢谢穆罕默德,但这个解决方案对我不起作用,因为Laravel 5.4
我的另一个表已经存在,这里有不同的情况,我发现的可能对某些人有所帮助。
Schema::table('objects', function (Blueprint $table) {
$table->integer('holding_id')->unsigned()->index()->nullable();
$table->foreign('holding_id')->references('id')->on('holdings');
});
with index()
and nullable()
it made the trick.
与index()
和nullable()
它做的伎俩。
EditNo need for index()
it just need to be nullable()
编辑不需要index()
它只需要nullable()
回答by ajit
To adding a foreign key, first make sure your column is marked as unsigned.
要添加外键,首先确保您的列标记为未签名。
Just add a line before your line:
只需在您的行之前添加一行:
$table->integer('holding_id')->unsigned();
$table->foreign('holding_id')->references('id')->on('holdings')->onDelete("NO ACTION");