Laravel在非主域上的自动增量

时间:2018-12-18 07:58:34

标签: laravel laravel-5.7

有我的移民。我希望id字段自动递增,但不是主要字段。可能吗?此迁移引发异常Syntax error or access violation: 1075 Incorrect table definition; there can be only one auto column and it must be defined as a key

Schema::create('tests', function (Blueprint $table) {
    $table->increments('id');
    $table->unsignedInteger('project_id');
    $table->unsignedInteger('model_id'); 
    $table->timestamps();

    $table->dropPrimary('id');

    $table->foreign('project_id')
        ->references('id')
        ->on('projects')
        ->onDelete('cascade');

    $table->primary(['project_id', 'model_id']);
});

2 个答案:

答案 0 :(得分:1)

这不是Laravel错误。您不能在mysql表中有两个自动递增列。 (当然,如果您使用的是mysql),但我认为任何关系数据库都无法提供两个自动增量列。

但是还有另一种方法。 看看this问题

答案 1 :(得分:1)

这不是Laravel错误,而是MySQL错误。如错误消息所述:it must be defined as a key。您将在primaryKey列上删除id约束。您应该尝试将其设置为索引。

尝试以下$table->unsignedInteger('id')->index()->autoIncrement();。这将使它成为AI整数,也将是索引,但不是PK。