【问题标题】:Setting a foreign key bigInteger to bigIncrements in Laravel 5.4在 Laravel 5.4 中将外键 bigInteger 设置为 bigIncrements
【发布时间】:2017-07-15 12:19:08
【问题描述】:

所以我试图在我的迁移文件中为 laravel 设置一个外键,这样用户表就很简单,但我试图使用 bigIncrements 而不是这样的站立增量。

 public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->engine = 'InnoDB';
        $table->bigIncrements('id')->unsigned();
        $table->string('user_id')->unique();
        $table->string('avatar');
        $table->string('name');
        $table->string('email')->unique();
        $table->string('password')->nullable();
        $table->rememberToken();
        $table->timestampsTz();
    });
}

当我做另一个表时,我尝试向它添加外键,我收到一个错误,说外键格式不正确。我对如何匹配感到困惑,因为我正在匹配列类型。这是另一张桌子。

public function up()
{
    Schema::create('social_logins', function (Blueprint $table) {
        $table->engine = 'InnoDB';
        $table->bigIncrements('id');
        $table->bigInteger('user_id')->unsigned();
        $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade')->unsigned()->index();
        $table->string('provider', 32);
        $table->string('provider_id');
        $table->string('token')->nullable();
        $table->string('avatar')->nullable();
        $table->timestamps();
    });
}

【问题讨论】:

  • 尝试去掉外键语句末尾的->unsigned()->index()

标签: php mysql laravel laravel-5


【解决方案1】:

原因是 primaryforeign 引用必须是同一类型。

bigIncrements() 想要unsignedBigInteger()

increments() 想要unsignedInteger()

如果你正在使用

$table->bigIncrements('id'); 作为用户表中的主键:

然后使用

$table->unsignedBigInteger('user_id'); as foreign key

如果您使用$table->increments('id'); 作为用户表中的主键,请使用

$table->unsignedInteger('user_id'); as freign key.



$table->increments(); creates just integer and $table->bigIncrements(); creates big integer. 

所以引用类型必须相同。

阅读更多https://laravel.com/docs/4.2/schema#adding-columns

【讨论】:

    【解决方案2】:

    从以下位置删除 unsigned()

    $table->bigIncrements('id')->unsigned();
    

    另一个迁移应该是这样的:

    $table->bigInteger('user_id')->unsigned();
    $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
    ....
    $table->index('user_id');
    

    【讨论】:

    • 非常感谢您这样做。
    • 或者干脆使用unsignedBigInteger
    【解决方案3】:

    问题是bigIncrements 返回一个无符号大整数。 为了工作,外键必须是带有index() 的无符号大整数。

    【讨论】:

      猜你喜欢
      • 2021-12-02
      • 2018-07-08
      • 2022-01-12
      • 1970-01-01
      • 2020-12-02
      • 2017-12-05
      • 2018-08-30
      • 2017-05-31
      • 1970-01-01
      相关资源
      最近更新 更多