[英]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.