簡體   English   中英

Laravel 6:SQLSTATE [HY000]:常規錯誤:1215無法添加外鍵約束

[英]Laravel 6: SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint

嘿,我目前正在Laravel 6數據庫遷移中工作,但是當我執行php artisan migration:fresh時,以下錯誤向我跳來跳去: SQLSTATE [HY000]:常規錯誤:1215無法添加外鍵約束(SQL:更改表category_post添加約束category_post_category_id_foreign外鍵( category_id )引用idcategories上的級聯更新上刪除級聯))

我檢查了以下內容:

  • 錯別字
  • 引用順序錯誤
  • 從Laravel 5.8起從增量更改為bigIncrement
  • 類型錯誤

這是我的遷移代碼,希望您能看到我犯的錯誤,因為我找不到它。

        // Table for storing Blog Posts
        Schema::create('posts', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('title');
            $table->string('slug');
            $table->string('read_time');
            $table->string('summary');
            $table->string('body');
            /*$table->timestamps('created_at');
            $table->timestamps('updated_at');*/
            $table->timestamps();
        });

        // Table for storing categories
        Schema::create('categories', function (Blueprint $table) {
          $table->bigIncrements('id');
          $table->string('name')->unique();
          $table->string('slug')->unique();
          $table->string('description');
          $table->timestamps();
        });

        // Table for association of Categories with Blog Posts
        Schema::create('category_post', function (Blueprint $table) {
          $table->bigInteger('category_id');
          $table->bigInteger('post_id');

          $table->foreign('category_id')->references('id')->on('categories')
            ->onUpdate('cascade')->onDelete('cascade');
          $table->foreign('post_id')->references('id')->on('posts')
            ->onUpdate('cascade')->onDelete('cascade');

          $table->primary(['post_id', 'category_id']);
        });

        // Table for association of Users with Blog Posts
        Schema::create('user_post', function (Blueprint $table) {
          $table->bigInteger('user_id');
          $table->bigInteger('post_id');

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

          $table->primary(['user_id', 'post_id']);
        });

畢竟,目標是將類別和用戶與帖子相關聯,以便我可以在帖子中包含標簽和用戶。

預先感謝您的幫助和幫助,我對Laravel還是很陌生,但是我對PHP有很好的了解,因此,如果您能解釋我做錯了的話,那將是非常不錯的:)

根據文檔bigIncrements表示:

自動遞增UNSIGNED BIGINT(主鍵)等效列。

因此,您的外鍵需要與之匹配( unsignedBigInteger() )。

暫無
暫無

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

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