簡體   English   中英

(錯誤號:150“外鍵約束格式不正確”)

[英](errno: 150 “Foreign key constraint is incorrectly formed”)

在此處輸入圖片說明 我是Laravel的新手。 我之前已經創建了users表。 在遷移中創建了employment表。 在下一次遷移中,我將使用alter users表將employment表中的job_id添加到users表中。 當我運行遷移時,會出現上述錯誤。

注:我需要給job_idemploymentusers表作為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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM