簡體   English   中英

SQLSTATE[HY000]:一般錯誤:1005 無法創建表 Laravel 8

[英]SQLSTATE[HY000]: General error: 1005 Can't create table Laravel 8

Schema::create('menus', function (Blueprint $table) {
    $table->id();
    $table->string('name')->unique();
    $table->string('slug')->unique();
    $table->integer('price');
    $table->text('description');
    $table->timestamps();
});

Schema::create('categories', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name')->unique();
    $table->string('slug')->unique();
    $table->timestamps();
});

Schema::create('category_menu', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('menu_id')->unsigned()->nullable();
    $table->foreign('menu_id')->references('id')
        ->on('menus')->onDelete('cascade');
    $table->integer('category_id')->unsigned()->nullable();
    $table->foreign('category_id')->references('id')
        ->on('categories')->onDelete('cascade');
    $table->timestamps();
});

當我運行php artisan:migrate時,出現以下錯誤。

SQLSTATE[HY000]: General error: 1005 Can't create table `mieaceh`.`category_menu` (errno: 150 "Foreign key constraint is wrongly forms") (SQL: alter table `category_menu` add constraint `category_menu_menu_id_foreign`外鍵( `menu_id`) 在刪除級聯時引用`menus` (`id`)

這是由於外鍵列和被引用列的數據類型很可能不匹配

當您使用$table->id()創建主鍵時,自動遞增 id 列的數據類型是unsignedBigInteger因此您必須具有相同數據類型的外鍵

Schema::create('category_menu', function (Blueprint $table) {
        $table->id();

        $table->unsignedBigInteger('menu_id');
        $table->foreign('menu_id')->references('id')
            ->on('menus')->onDelete('cascade');

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

        $table->timestamps();
});

您不應該將 pivot 表中的列設置為可以為外鍵為空以保持數據完整性。

還要與主鍵列的數據類型和定義保持一致——使用$table->id()時,在所有表的所有遷移中保持一致。 這樣,在將外鍵定義為$table->unsignedBigInteger()時,您將有更少的不匹配機會

laravel 遷移文件包含一個日期時間段,用於確定首先遷移哪個文件

注意順序

2021_10_11_101533_create_posts_table.php
2014_10_12_000000_create_users_table.php

當你跑步時

php artisan migrate 

帖子表將首先遷移,它包含一個外鍵

用戶身份

它引用用戶表上的主鍵

ID

但是用戶表還不存在,要解決此問題,請更改文件名並確保用戶表首先像這樣遷移

注意順序

2014_10_10_000000_create_users_table.php
2021_10_11_101533_create_posts_table.php

用於聲明外鍵的簡短模式

$table->foreignId('user_id')->constrained()->cascadeOnDelete();

暫無
暫無

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

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