【问题标题】:how to set Foreign key constraint is incorrectly formed in laravel 5.8 [duplicate]如何在laravel 5.8中设置外键约束不正确[重复]
【发布时间】:2019-04-23 06:19:32
【问题描述】:

我有一些表要迁移,后面还有。如果我尝试将该表迁移到服务器数据库,它会显示一般错误:1005。 我在底部给出错误和服务器详细信息。请帮助我顺利迁移。

1.)用户

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

2.)公司

Schema::create('companies', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->longText('description');
            $table->unsignedInteger('user_id');
            $table->timestamps();

            $table->foreign('user_id')->references('id')->on('users');
        });

3.项目

Schema::create('projects', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->longText('description');
            $table->unsignedInteger('company_id');
            $table->unsignedInteger('user_id');
            $table->timestamps();

            $table->foreign('user_id')->references('id')->on('users');
            $table->foreign('company_id')->references('id')->on('companies');
        });

服务器详情

server: 127.0.0.1 via TCP/IP
Server type: MariaDB
Server connection: SSL is not being used Documentation
Server version: 10.1.38-MariaDB - mariadb.org binary distribution
Protocol version: 10
User: root@localhost
Server charset: UTF-8 Unicode (utf8)
DB Name: laravel

错误:

 Illuminate\Database\QueryException  : SQLSTATE[HY000]: General error: 1005 Can't create table `laravel`.`#sql-91c_30` (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table `companies` add constraint `companies_user_id_foreign` foreign key (`use
r_id`) references `users` (`id`))

【问题讨论】:

    标签: php mysql mariadb laravel-5.8


    【解决方案1】:

    正如我所见,当您创建 bigInteger 的 PK 和整数的外键时,存在数据类型不匹配的问题,

    Schema::create('companies', function (Blueprint $table) {
    ...
    $table->unsignedBigInteger('user_id');
    });
    

    在其他表格中

    Schema::create('projects', function (Blueprint $table) {
    ...
    $table->unsignedBigInteger('company_id');
    $table->unsignedBigInteger('user_id');
    });
    

    执行此操作并再次检查。

    【讨论】:

    • 外键是unsignedInteger。还是不匹配。
    • 这是我唯一关心的问题。外键是unsignedInteger,应该是unsignedBigInteger,因为外表的PK是bigIntegers
    猜你喜欢
    • 2020-11-12
    • 2020-10-23
    • 2017-10-03
    • 2019-07-25
    • 1970-01-01
    • 2017-10-04
    • 1970-01-01
    • 2018-02-19
    • 2021-05-26
    相关资源
    最近更新 更多