这就是我的迁移。我希望
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']);
});
这不是
Laravel
错误。 mysql 表中不能有两个自动增量列。 (当然,如果您使用的是 mysql),但我认为没有任何关系数据库能够让您拥有两个自动增量列。
但是还有另一种方法可以做到这一点。 看看这个问题
这不是 Laravel 错误,而是 MySQL 错误。正如错误消息所示:
it must be defined as a key
。您正在删除 primaryKey
列上的 id
约束。您应该尝试将其设置为索引。
尝试以下
$table->unsignedInteger('id')->index()->autoIncrement();
。这将使它成为一个 AI 整数,也是一个索引,但不是 PK。
它看起来是使用原始 SQL 的最简单方法。我发现的另一种方法不起作用。
use Illuminate\Support\Facades\DB;
Schema::table('table', function (Blueprint $table) {
DB::statement('ALTER TABLE `table` ADD `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT FIRST, ADD INDEX `id` (`id`);');
});