Lumen/Laravel - Eloquent: 迁移带有未签名的 BIGINT 作为 PK 和 FK 的表

Lumen/Laravel - Eloquent: Migration of tables with BIGINT unsigned as PK and FK

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

Ad_users

Ad_groups

Ad_usersxad_groups

后者显然是一个连接点table,仅包含两个引用另外两个 table 的主键的 FK。 现在,我有以下问题,这是 ad_users table:

的迁移
<?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'); 创建了一个 bigint(20) unsigned 类型的列。 包含 FK 的联结 table 中的列当然必须是完全相同的类型。 但是,外键当然不能是联结 table 的主键,因此我不能使用 $table->bigIncrements 语法,但必须使用 $table->bigInteger 语法,如下所示Ad_usersxad_groups table:

的迁移
<?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 在原始 table 的 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`))

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

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

此函数称为列修饰符。您可以检查以下 link 以获得列修饰符的完整列表。 Laravel Database Migrations - Columns Modifiers