首页 > 解决方案 > Lumen/Laravel - Eloquent:迁移 BIGINT 未签名为 PK 和 FK 的表

问题描述

我想迁移一个包含三个表的数据库:

Ad_users

广告组

Ad_usersxad_groups

后者显然是一个联结表,仅包含两个引用其他两个表的 PK 的 FK。现在,我有以下问题,这是 ad_users 表的迁移:

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateAdusersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('Ad_users', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('common_name');
            $table->string('location');
            $table->string('description');
            $table->integer('postalcode');
            $table->string('physical_delivery_office_name');
            $table->string('telephone_number');
            $table->string('initials');
            $table->string('street_address');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('Ad_users');
    }
}

$table->bigIncrements('id');创建一个 Columnbigint(20) unsigned类型。包含 FK 的联结表中的列当然必须是完全相同的类型。但是,外键当然不能是联结表的主键,因此我不能使用$table->bigIncrements语法,但 instad 必须使用$table->bigInteger语法,如在 Ad_usersxad_groups 表的迁移中所示:

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateAdusersxadgroupsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('Ad_usersxad_groups', function (Blueprint $table) {
            $table->bigInteger('Ad_user_id');
            $table->bigInteger('Ad_group_id');
            $table->foreign('Ad_user_id')->references('id')->on('Ad_users');
            $table->foreign('Ad_group_id')->references('id')->on('Ad_groups');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('Ad_usersxad_groups');
    }
}

出现的问题: $table->bigInteger创建一个类型的列bigint(20)。这似乎与 bigint(20) unsigned原始表的 PK 列中的类型不兼容。当我尝试运行迁移时,Artisan 引发以下错误:

 SQLSTATE[HY000]: General error: 1005 Can't create table `aetherdb`.`ad_usersxad_groups` (errno: 150 "Foreign key constraint is incorrectly fo
  rmed") (SQL: alter table `Ad_usersxad_groups` add constraint `ad_usersxad_groups_ad_user_id_foreign` foreign key (`Ad_user_id`) references `A
  d_users` (`id`))

bigint(20) unsigned除了从原始表的 PK 列上移开类型之外,还有什么方法可以解决这个问题?我可以以某种方式将其添加unsigned到联结表中的非主键列吗?

标签: phplaraveleloquentmigrationlumen

解决方案


您可以使用$table->bigInteger('Ad_user_id')->unsigned();使此 FK 无符号。

此功能称为列修饰符。您可以查看以下链接以获取列修饰符的完整列表。Laravel 数据库迁移 - 列修饰符


推荐阅读