簡體   English   中英

一般錯誤:1005 無法創建表(錯誤號:150“外鍵約束格式不正確”)

[英]General error: 1005 Can't create table (errno: 150 "Foreign key constraint is incorrectly formed")

我在 Laravel 8 中有一個數據庫遷移,如下所示:

class CreateArticlesTable extends Migration
{
    public function up()
    {
        Schema::create('articles', function (Blueprint $table) {
            $table->id();
            $table->integer('user_id')->unsigned();
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->string('title');
            $table->string('slug');
            $table->text('description');
            $table->text('body');
            $table->string('imageUrl');
            $table->string('tags');
            $table->integer('viewCount')->default(0);
            $table->integer('commentCount')->default(0);
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('articles');
    }
}

但是每當我想運行它時,我都會收到此錯誤:

一般錯誤:1005 Can't create table elearning articles (錯誤號:150“外鍵約束格式不正確”)

我不知道這里到底出了什么問題,所以如果你知道如何解決這個問題,請告訴我......

而不是使用

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

利用

$table->unsignedBigInteger();

laravel 使用 20 位的 unsignedBigInteger,而 unsignedInteger 只需要 11 位

https://laravel.com/docs/8.x/migrations#foreign-key-constraints

用戶表和文章表的引擎是否相同並且都是InnoDB? MyISAM 不支持外鍵。 如果是,是在用戶表之后創建文章表嗎? 如果答案是肯定的,那么:這兩個字段是否完全屬於同一類型? 我認為您的用戶 ID 是自動遞增的,如果是,則添加未簽名的外鍵:

 $table->foreign('user_id')->unsigned()->references('id')->on('users')->onDelete('cascade');

試試這個 Laravel 8

$table->id();
 $table->unsignedBigInteger('user_id')->unsigned();
 $table->foreign('user_id')->on('users')->references('id')->onDelete('cascade');

暫無
暫無

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

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