Laravel应用切换为使用Uuid时Events表迁移失败:SQLSTATE[42000]多主键定义错误求助
解决Laravel迁移中“Multiple primary key defined”的问题
我一眼就看出问题出在哪了——你的events表迁移里的join_id字段定义踩了Laravel Blueprint方法的参数坑!
问题根源
Laravel的Blueprint::integer()方法里,第二个参数是控制字段是否自增的布尔值,而不是你以为的字段长度!你写的$table->integer('join_id', 6)->unique();,相当于把join_id设置成了自增字段。而MySQL里自增字段会被默认设为主键,这就和你已经定义的uuid('id')->primary()冲突,直接触发了“多个主键定义”的报错。
解决方案
把join_id的定义改成不含自增参数的格式,如果需要指定长度,用length()链式方法单独设置就行:
修正后的events表迁移代码:
Schema::create('events', function (Blueprint $table) { $table->uuid('id')->primary(); $table->string('title', 255); // 移除自增参数,按需设置字段长度 $table->integer('join_id')->length(6)->unique(); $table->string('image')->nullable(); $table->string('location')->nullable(); $table->text('description')->nullable(); $table->timestamp('event_date')->nullable(); $table->timestamp('event_time')->nullable(); $table->foreignUuid('user_id')->nullable()->index(); $table->foreign('user_id') ->references('id') ->on('users') ->onDelete('cascade'); $table->softDeletes(); $table->timestamps(); });
如果你的join_id不需要是有符号整数,更推荐用unsignedInteger(),这是业务场景里更常见的用法:
$table->unsignedInteger('join_id')->length(6)->unique();
小提醒
以后用Laravel的字段定义方法时,一定要注意参数顺序:
integer(string $column, bool $autoIncrement = false):第二个参数是自增开关,不是长度- 字段长度要通过
length(int $value)链式方法单独设置
改完之后重新跑迁移,应该就能顺利执行了!
内容的提问来源于stack exchange,提问作者Saiful Azam
相关产品推荐
相关产品推荐

