0

当您使用 laravel 迁移应用外键时,会出现此类错误

“外键约束格式不正确”

迁移的默认结构

User Table
---------

Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->timestamps();
        });

Chat Table
---------

 Schema::create('chats', function (Blueprint $table) {
            $table->id();
            $table->integer('user_id');
            $table->timestamps();

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


        });

4

1 回答 1

2

发生这种情况是因为我们的列大小不应该完全相同,请看下面。

$table->id();
This will create a big integer

 $table->integer('user_id');
This will create a small integer that's why Our foreign key relations fails

如何解决此问题

$table->unsignedBigInteger('user_id');

或者

$table->foreignId('user_id')->constrained();

添加 unsignedBigInteger ,您的问题将得到解决。

于 2020-09-04T08:12:16.427 回答