首页 > 解决方案 > 在外键约束“followers_ibfk_1”中引用列“follower_id”和引用列“id”不兼容。我的错误是什么?

问题描述

我正在尝试将 follower_id 连接到用户 id,而我得到的只是这个错误。谁能帮忙。这是我的代码:

 Schema::create('followers', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger("user_id");
            $table->foreignId("user_id")->constrainted()->onDelete();
            $table->unsignedBigInteger("follower_id");
            $table->foreignId("follower_id")->constrainted()->onDelete();
            $table->timestamps();
        });
    }


            $table->id();
            $table->string("username");
            $table->string("email");
           $table->string("password");
            $table->timestamps();
        });
    }

标签: phpmysqllaravelmigrationlaravel-8

解决方案


follower_id要将表引用users为外键,请尝试以下操作:

$table->unsignedBigInteger('follower_id');
$table->foreign('follower_id')->references('id')->on('users');

警告:

指令:

$table->foreignId("user_id")->constrainted();
// OR
$table->foreignId("follower_id")->constrainted();

是一个快捷方式:

$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users');
// OR
$table->unsignedBigInteger('follower_id');
$table->foreign('follower_id')->references('id')->on('followers');

https://laravel.com/docs/8.x/migrations#foreign-key-constraints


推荐阅读