Laravel中遇‘Multiple Primary Keys’错误,如何创建自增唯一非主键列?
解决Laravel迁移中「Multiple Primary Keys」错误,实现非主键自增唯一字段
错误原因
你最初的代码里,$table->integer('biometric_id', true)的第二个参数true是让字段自增,但Laravel的规则是:自增字段会被自动设置为主键。这就和你已经设置的employee_id主键冲突,触发「Multiple Primary Keys」错误。
可行解决方案
方法1:使用原生SQL语句修改字段(无需额外扩展)
先创建带唯一索引的普通整数字段,表创建完成后再修改为自增:
Schema::create('employees', function (Blueprint $table) { $table->string('employee_id', 150)->primary(); // 先创建无自增的整数字段,添加唯一索引(MySQL要求自增字段必须属于索引) $table->integer('biometric_id')->unsigned()->unique(); $table->string('employee_fname', 150)->nullable(); $table->string('employee_mname', 150)->nullable(); $table->string('employee_lname', 150)->nullable(); $table->string('employee_ext', 150)->nullable(); // 其他字段... }); // 表创建完成后,执行原生SQL修改字段为自增 DB::statement('ALTER TABLE employees MODIFY COLUMN biometric_id INT UNSIGNED NOT NULL AUTO_INCREMENT');
方法2:使用Laravel的change()方法(需依赖扩展)
如果想用Laravel的Schema语法实现,需要先安装doctrine/dbal扩展(用于字段修改):
composer require doctrine/dbal
然后编写迁移:
Schema::create('employees', function (Blueprint $table) { $table->string('employee_id', 150)->primary(); $table->integer('biometric_id')->unsigned()->unique(); $table->string('employee_fname', 150)->nullable(); $table->string('employee_mname', 150)->nullable(); $table->string('employee_lname', 150)->nullable(); $table->string('employee_ext', 150)->nullable(); // 其他字段... }); // 用change()方法修改字段为自增 Schema::table('employees', function (Blueprint $table) { $table->integer('biometric_id')->unsigned()->unique()->autoIncrement()->change(); });
为什么你之前的修改没生效?
你之前的代码把employee_id改成了unique(未设置主键),而且在Schema::create的闭包里执行DB::statement——此时表还在创建过程中,修改字段的语句无法正确执行。另外,缺少对「自增字段必须属于索引」的约束处理,导致修改失败。
内容的提问来源于stack exchange,提问作者Mark Unico
相关产品推荐
相关产品推荐

