繁体   English   中英

SQLSTATE[HY000]: General error: 1005 Can't create table `business`.`users` (errno: 150 "Foreign key constraint is incorrectly formed") Laravel 7

[英]SQLSTATE[HY000]: General error: 1005 Can't create table `business`.`users` (errno: 150 "Foreign key constraint is incorrectly formed") Laravel 7

我需要在用户(从 laravel 7 auth 脚手架创建)和类别之间创建一对多关系。 但是当我运行迁移时,我得到这个错误:迁移:2014_10_12_000000_create_users_table

照亮\数据库\查询异常

SQLSTATE[HY000]: General error: 1005 Can't create table business users (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table users add constraint users_category_id_foreign外键 ( category_id ) references catgories ( id ) on delete cascade)

这是用户模式:

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

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

    });

这是类别:

Schema::create('categories', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('category');
        $table->timestamps();
    });

我做了一些搜索,我发现这种错误有两个原因,第一个是类别表迁移应该在用户表之前完成,第二个是用户模式上的类别 id 数据类型和类别中的一个 id 必须相同,我验证了这两个条件,但我仍然遇到相同的错误。 如果有人能告诉我出了什么问题,我将不胜感激!

更改on('categories')而不是on('catgories')你写了catgories 但它必须是categories

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

当外键的类型与主键的类型不匹配时,就会发生这种情况。

确保category_id的类型和长度与类别表类别的主键完全相同。 因此,如果您声明为无符号大 integer,请确保categories.id为无符号大 integer。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM