首页 > 解决方案 > Laravel 迁移无法创建关系

问题描述

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

Illuminate\Database\QueryException : SQLSTATE[HY000]: General error: 1005 Can't create table larasocial#sql-1710_1f5(errno: 150 "Foreign key constraint is wrongly forms") (SQL: alter table friend_requestsadd constraint friend_requests_sender_id_foreignforeign key ( sender_id) references users( id) on delete cascade on update cascade)

用户迁移文件

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

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

标签: mysqllaravel

解决方案


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

为未来的观众编辑:

  • 将两列更改为unsignedBigInteger

推荐阅读