繁体   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