Laravel迁移报错:SQLSTATE[42000] 主键重复定义求助
Laravel迁移报错:1068 Multiple primary key defined 解决方法
错误原因
触发SQLSTATE[42000]: 1068 Multiple primary key defined错误的核心原因是重复定义主键。
Laravel的$table->id()是封装好的快捷方法,它会自动创建unsignedBigInteger类型的id字段,同时默认将其设为表的主键并开启自增属性。而你在Users表和Questions表的迁移代码中,额外调用了->primary()方法,这就导致MySQL收到两次设置主键的指令,触发语法错误。
解决步骤
1. 移除重复的主键定义
直接修改Users表和Questions表的迁移代码,删除多余的->primary()调用:
修改后的Users表迁移代码:
Schema::create('users', function (Blueprint $table) { $table->id(); // 已自动设置主键,无需重复调用->primary() $table->text('name'); $table->enum('role', ['admin', 'user'])->default('user'); $table->string('password'); $table->timestamps(); });
修改后的Questions表迁移代码:
Schema::create('questions', function (Blueprint $table) { $table->id(); // 移除->primary() $table->unsignedBigInteger('user_id'); $table->text('title'); $table->text('name'); $table->text('description'); $table->text('body'); $table->timestamps(); }); Schema::table('questions', function (Blueprint $table) { $table->foreign('user_id')->references('id')->on('users'); });
2. 确认迁移执行顺序
本次错误并非迁移顺序导致,但外键关联依赖父表先存在,需保证迁移文件的时间戳前缀顺序正确:
- Users表迁移文件前缀最早(例:
2024_01_01_000000_create_users_table.php) - Questions表迁移前缀早于Comments表(例:
2024_01_01_000001_create_questions_table.php) - Comments表迁移前缀最晚(例:
2024_01_01_000002_create_comments_table.php)
Laravel会按文件名的时间戳顺序执行迁移,确保父表先创建,避免外键创建失败。
3. 重新执行迁移
完成修改后,运行命令重新生成表结构:
php artisan migrate:fresh
内容的提问来源于stack exchange,提问作者Mario Mancev
相关产品推荐
相关产品推荐

