簡體   English   中英

Laravel 遷移一般錯誤:1215 無法添加外鍵約束 Laravel 7.x

[英]Laravel migration General error: 1215 Cannot add foreign key constraint Laravel 7.x

我想在我的 laravel 7.x 應用程序上使用兩個模型:用戶和圖像:

# Users migration : 2014_10_12_000000_create_users_table.php

Schema::create('users', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('name');
        $table->string('email')->unique();
        $table->timestamp('email_verified_at')->nullable();
        $table->string('password');
        $table->rememberToken();
        $table->timestamps();
    });

# Images migration : 2020_03_27_121254_create_models_images_table
Schema::create('images', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->bigInteger('user_id')->unsigned;
        $table->string('name');
        $table->timestamps();
    });

    Schema::table('images', function (Blueprint $table) {
        $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
    });

嘗試遷移時,我收到以下錯誤:一般錯誤:1215 無法添加外鍵約束(SQL:alter table images添加約束images_user_id_foreign外鍵( user_id )在刪除級聯上引用usersid ))

我已經在谷歌上搜索過但沒有成功,有人可以幫助我嗎?

謝謝

問題

您沒有正確設置unsigned

解決方案

代替:

$table->bigInteger('user_id')->unsigned;

經過:

$table->bigInteger('user_id')->unsigned();

解釋

由於user_id未簽名,因此定義與users表的id不匹配,這意味着您無法設置外鍵。

Laravel 7.x 之前

你也可以這樣做:

$table->unsignedBigInteger('user_id');

Laravel 7.x

從 Laravel 7 開始,您可以在users遷移中這樣做:

Schema::table('users', function (Blueprint $table) {
    $table->id();
    // ...
});

在您的images遷移中:

Schema::table('users', function (Blueprint $table) {
    // ...
    $table->foreignId('user_id')->constrained();
});

您可以在此處找到更多信息:https ://laravel.com/docs/7.x/migrations#foreign-key-constraints

您在unsiged()中缺少括號

根據Laravel 文檔

->unsigned()INTEGER列設置為UNSIGNED (MySQL)

改變

 $table->bigInteger('user_id')->unsigned;

$table->bigInteger('user_id')->unsigned();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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