Laravel迁移添加外键给出错误的外键(`user_id`)

时间:2019-06-04 04:35:46

标签: laravel-5 database-migration

当我php artisan migrate时出现错误,请参见下文。 订单迁移是用户,公司和枢纽迁移。

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

我该怎么办?

User.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();
    });

Companies.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)

1 个答案:

答案 0 :(得分:1)

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

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

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

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

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

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');
});