繁体   English   中英

无法在laravel中创建表“一般错误:1个表具有多个主键”

[英]Can't create table in laravel “General error: 1 table has more than one primary key”

当使用以下命令php artisan migrate它将返回以下错误:

常规错误:1个表-具有多个主键

我试图使用强制主键

$table->primary('id');

注意:在另一个表中引用的ID也是数据类型bigIncrements

Schema::create('stuff', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('class'); 
        $table->timestamps();
        $table->bigIncrements('owner');
        $table->float('price');
        $table->bigIncrements('teacher');
        $table->foreign('owner')->references('id')->on('othertable');
        $table->foreign('teacher')->references('id')->on('othertable');
    });
}

您使用bigIncrements而不是整数

bigIncrements创建主键

如果ownersteachers表具有bigIncrements id列,那么将迁移代码替换为:

Schema::create('stuff', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('class'); 
        $table->timestamps();
        $table->unsignedBigInteger('owner');
        $table->float('price');
        $table->unsignedBigInteger('teacher');
        $table->foreign('owner')->references('id')->on('othertable');
        $table->foreign('teacher')->references('id')->on('othertable');
    });
}

您应该将所有者和老师bigInteger

Schema::create('stuff', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('class'); 
        $table->timestamps();
        $table->bigInteger('owner')->unsigned();
        $table->float('price');
        $table->bigInteger('teacher')->unsigned();
        $table->foreign('owner')->references('id')->on('othertable');
        $table->foreign('teacher')->references('id')->on('othertable');
    });
}

显然, Laravel中的bigIncrements数据类型将使该字段成为主键 在这种情况下,您具有三个主键,分别是ID,所有者和教师字段。 要从主键中删除最后两个,请在迁移文件中添加以下代码。

Schema::table('stuff', function (Blueprint $table) {
    $table->dropPrimary('owner');
    $table->dropPrimary('teacher');
});

另外,如果这两个字段(所有者,教师)是参考字段,那么我想您不需要为它们提供bigIncrements的数据类型。 将它们更改为unsignedBigInteger可能是一个更好的选择。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM