I am trying to add FK 'module_id' to my table '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
))
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
))
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();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.