[英]Laravel - Cannot add foreign key constraint
I am trying to add FK 'module_id' to my table 'documents'.我正在尝试将 FK 'module_id' 添加到我的表 'documents' 中。 I have ran the following query:我已经运行了以下查询:
public function up()
{
Schema::table('documents', function (Blueprint $table) {
$table->integer('module_id')->unsigned();
$table->foreign('module_id')->references('id')->on('modules');
});
}
The following error is being returned:正在返回以下错误:
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table
documents
add constraintdocuments_module_id_foreign
foreign key (module_id
) referencesmodules
(id
)) SQLSTATE[HY000]:一般错误:1215 无法添加外键约束(SQL:alter tabledocuments
添加约束documents_module_id_foreign
module_id
外键(module_id
)引用modules
(id
))
I'm not sure what I'm doing wrong, I'm sure it is probably a silly mistake but I have spent a lot of time going around in circles trying to figure it out... here is what I have tried..我不确定我做错了什么,我确定这可能是一个愚蠢的错误,但我花了很多时间在圈子里试图弄清楚......这是我尝试过的......
I have included a picture of my DB tables, i appreciate any help.我已经包含了我的数据库表的图片,我感谢任何帮助。
Update:更新:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (
laravel
.#sql-2cd_23
, CONSTRAINTdocuments_module_id_foreign
FOREIGN KEY (module_id
) REFERENCESmodules
(id
)) (SQL: alter tabledocuments
add constraintdocuments_module_id_foreign
foreign key (module_id
) referencesmodules
(id
)) SQLSTATE[23000]:完整性约束违规:1452 无法添加或更新子行:外键约束失败(laravel
。#sql-2cd_23
,CONSTRAINTdocuments_module_id_foreign
#sql-2cd_23
FOREIGN KEY(module_id
)REFERENCESmodules
(id
))(SQL:更改表documents
添加约束documents_module_id_foreign
module_id
外键(module_id
)引用modules
(id
))
The type of the column needs to be a big integer.列的类型需要是一个大整数。
Schema::table('documents', function (Blueprint $table) {
$table->unsignedBigInteger('module_id');
$table->foreign('module_id')->references('id')->on('modules');
});
Update更新
You probably already got data in your tables, since the column can't be null the foreign key can't exists.您可能已经在表中获得了数据,因为该列不能为空,因此外键不能存在。 Starting it out as nullable then adding the relationships and removing the nullable would fix it.将其作为可为空开始,然后添加关系并删除可为空的将修复它。 So:所以:
$table->unsignedBigInteger('module_id')->nullable();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.