[英]Laravel Table Migration: Cannot add foreign key constraint
我正在尝试在 Laravel 中创建外键但是当我使用 artisan 迁移我的表时,我抛出了以下错误:
模块迁移表:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateModulesTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up() {
Schema::create('modules', function (Blueprint $table) {
$table->id();
$table->string('module_name');
// foreign key
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down() {
Schema::dropIfExists('modules');
}
}
课程迁移表:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateLessonTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up() {
Schema::create('lesson', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->integer('module_id')->unsigned();
$table->text('content');
$table->integer('created_by')->unsigned();
$table->integer('updated_by');
$table->string('enabled');
$table->string('position');
$table->timestamps();
});
Schema::table('lesson', function(Blueprint $table) {
$table->foreign('module_id')->references('id')->on('modules');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down() {
Schema::dropIfExists('lesson');
}
}
关于我做错了什么的任何想法,我现在想得到这个,因为我有很多需要创建的表,例如用户、客户、项目、任务、状态、优先级、类型、团队。 理想情况下,我想创建使用外键保存这些数据的表,即 clients_project 和 project_tasks 等。
希望有人可以帮助我开始。
为 module_id 列添加 unsignedBigInteger
Schema::create('lesson', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->unsignedBigInteger('module_id');
$table->text('content');
$table->integer('created_by')->unsigned();
$table->integer('updated_by');
$table->string('enabled');
$table->string('position');
$table->timestamps();
$table->foreign('module_id')->references('id')->on('modules');
});
你的foreign_key
字段和你的id
应该是相同的类型,例如,如果modules.id
是bigIncrements
,你的Lesson
表中的foreign_key
也应该是bigInteger
。
课程迁移文件
Schema::create('lesson', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->integer('module_id')->unsigned()->nullable();
$table->foreign('module_id')->references('id')->on('modules')->onDelete('cascade');
$table->text('content');
$table->integer('created_by')->unsigned();
$table->integer('updated_by');
$table->string('enabled');
$table->string('position');
$table->timestamps();
});
注意:您应该确保您的模块表迁移在课程表迁移之前运行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.