Laravel迁移无法建立关系

时间:2019-12-21 16:44:09

标签: mysql laravel

我有2个表,用户和Friendly_requests,我想创建外键,但出现以下错误。

  

Illuminate \ Database \ QueryException:SQLSTATE [HY000]:常规错误:1005无法创建表larasocial#sql-1710_1f5(错误号:150“外键约束格式不正确”)(SQL:更改表friend_requests添加约束friend_requests_sender_id_foreign外键(sender_id)引用usersid)在更新级联上删除级联)

用户迁移文件

<?php

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

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string("name", 255);
            $table->string("surname", 255);
            $table->string("email", 255);
            $table->string("password", 255);
            $table->date("birthday");
            $table->string("gender", 255);
            $table->string("photo", 255);
            $table->integer("recover_code")->default(0);
            $table->boolean("confirmed")->default(false);
            $table->dateTime("last_visit");
            $table->date("created_at");
        });
    }

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

friend_requests迁移文件

<?php

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

class CreateFriendRequestsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('friend_requests', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->integer("sender_id");
            $table->integer("accepter_id");

            $table->foreign("sender_id")->references("id")->on("users")->onDelete("cascade")->onUpdate("cascade");
            $table->foreign("accepter_id")->references("id")->on("users")->onDelete("cascade")->onUpdate("cascade");
        });
    }

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

我已经尝试过其他类似问题的方法,但是它们并不能解决我的问题。

1 个答案:

答案 0 :(得分:5)

外键列必须与其指向的引用具有相同的数据类型。由于您的用户ID是大整数,因此您的参考字段也必须是大整数。

为将来的观看者编辑:

  • 将两列都更改为import hello.mod1; import hello.mod2