【问题标题】:Laravel migration add foreign key gives error foreign key (`user_id`)Laravel 迁移添加外键给出错误外键(`user_id`)
【发布时间】:2019-10-19 14:26:54
【问题描述】:

当我 php artisan migrate 时,我收到一个错误,见下文。 订单迁移是用户、公司和数据中心迁移。

当我删除user 时,所有companies 都必须删除,当我删除company 时,所有users 都必须删除。

我做错了什么?

用户.php

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

公司.php

    Schema::create('companies', function (Blueprint $table) {
        $table->engine = "InnoDB";
        $table->increments('id')->unsigned();
        $table->string('companyname');
        $table->string('address');
        $table->integer('housenumber');
        $table->string('postalcode');
        $table->string('city');
        $table->string('province');
        $table->string('email');
        $table->string('phonenumber');
        $table->timestamps();
    });

CreateUserCompanyPivotTable.php

    Schema::create('user_company', function (Blueprint $table) {
        $table->engine = "InnoDB";
        $table->integer('user_id')->unsigned();
        $table->integer('company_id')->unsigned();
    });

    Schema::table('user_company', function (Blueprint $table) {
        $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
        $table->foreign('company_id')->references('id')->on('companies')->onDelete('cascade');
    });

错误:

Illuminate\Database\QueryException  : SQLSTATE[HY000]: General error: 1215 

Cannot add foreign key constraint (SQL: alter table `user_company` add constraint `user_company_user_id_foreign` foreign key (`user_id`) references `users` (`id`) on delete cascade)

【问题讨论】:

    标签: laravel-5 database-migration


    【解决方案1】:

    迁移失败,因为user_companyuser_id 的数据类型与users 中的id 不匹配。

    您在users 表中使用了bigIncrement(),它创建了一个auto_increment 字段,类型为UNSIGNED BIGINT

    user_company 表中,您使用integer()->unsigned() 创建user_id,这将创建一个以UNSIGNED INT 为类型的auto_increment 字段。

    MySQL 在创建外键时需要两个字段类型相同。

    要解决此问题,您应该使用bigInteger()->unsigned() 创建user_id

    Schema::create('user_company', function (Blueprint $table) {
        $table->engine = "InnoDB";
        $table->bigInteger('user_id')->unsigned();
        $table->bigInteger('company_id')->unsigned();
        // You don't need separate schema code to create foreign
        $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
        $table->foreign('company_id')->references('id')->on('companies')->onDelete('cascade');
    });
    

    【讨论】:

    • 我也将 company.id 更改为 bigInteger 并像魅力一样工作,谢谢!
    猜你喜欢
    • 2019-02-09
    • 2019-01-31
    • 2014-09-27
    • 2018-08-01
    • 2018-09-22
    • 2016-07-06
    • 2015-08-14
    • 2020-01-20
    • 1970-01-01
    相关资源
    最近更新 更多