Laravel中外键约束的格式不正确

时间:2020-08-08 13:00:15

标签: php mysql laravel

Laravel 7. PHP 7.4

嗨! 我正在处理数据库,试图在另一个表中为用户生成外键时突然陷入了问题。 这应该是一个直接的过程,我正在关注文档,仍然出现错误。

General error: 1005 Can't create table `carchain_qrcode`.`sellers` (errno: 150 "Foreign key constraint is incorrectly formed

用户表

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->bigInteger('id');
        $table->string('name')->unique();
        $table->string('email')->unique();
         });
}

卖家表

public function up()
{
    Schema::create('sellers', function (Blueprint $table) {
        $table->bigInteger('id');
        $table->unsignedBigInteger('user_id');
        $table->string('seller_name');
        $table->string('seller_email');

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

    });

有人可以指出我做错了什么。 谢谢

3 个答案:

答案 0 :(得分:6)

我认为问题在于您的用户表的 id bigInteger ,而不是 bigIncrements 或< strong> unsignedBigInteger 。
在Laravel 7中,您可以简单地执行以下操作: $ table-> id()创建id列。

答案 1 :(得分:4)

此错误是由于要创建的外键上使用的数据类型不正确而发生的。 users table上的主键数据类型应与您在Sellers table中使用的数据类型相同,如下所示:

用户表

$table->id();

卖家表

$table->unsignedBigInteger('user_id');

或者如果您在用户表主键上使用了任何其他数据类型,则另一个表中的外键应相应相同。

答案 2 :(得分:4)

简短:有关快速修复的信息,请参见@ Aless55答案。要记住的主要事情是idforeign_key列类型应该匹配。

正确的方式: 最好使用Laravel的内置API创建primary keyforeign key。此处有更多详细信息: 它将自动处理列类型,创建索引等。此外,坚持使用官方文档可以使他人容易理解代码,并由开发人员进行维护(这只是我的看法)。

在您的情况下:

用户表

public function up()
{
    Schema::create('users', function (Blueprint $table) {
       $table->id();
       $table->string('name')->unique();
       $table->string('email')->unique();
     });
}

卖家表:

public function up()
{
    Schema::create('sellers', function (Blueprint $table) {
       $table->id();
       $table->foreignId('user_id')->constrained(); // this will automatically detect which table to reference
       $table->string('seller_name');
       $table->string('seller_email');
     });
}