[英](errno: 150 “Foreign key constraint is incorrectly formed”)
我是Laravel的新手。 我之前已經創建了users
表。 在遷移中創建了employment
表。 在下一次遷移中,我將使用alter users
表將employment
表中的job_id
添加到users
表中。 當我運行遷移時,會出現上述錯誤。
注:我需要給job_id
在employment
表users
表作為job_id
。 soumya是我的數據庫名稱
當我在沒有外鍵約束的情況下運行遷移時,它可以完美運行。
遷移:就業表
public function up()
{
Schema::create('employment', function (Blueprint $table) {
$table->increments('job_id');
$table->string('job_title');
$table->string('job_description')->nullable()->default(NULL);
$table->string('slug')->unique();
$table->timestamps();
});
}
public function down()
{
Schema::drop('employment');
}
遷移更改users
表
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->integer('job_id')->after('deleted');
$table->foreign('job_id')->references('job_id')->on('employment');
});
}
public function down()
{
Schema::table('users', function (Blueprint $table) {
$table->dropForeign('users_job_id_foreign');
$table->dropColumn('job_id');
});
}
像這樣更改您的用戶遷移
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->unsignedInteger('job_id');
$table->foreign('job_id')->references('job_id')->on('employment');
});
}
在laravel中,表以先到先得的方式遷移。 確保包含外鍵的表之前已遷移您的外鍵所引用的表。
為此,您可以更改遷移文件的名稱,以便在遷移項目表中的項目表之前先存在用戶表的遷移。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.