Azure中Laravel迁移失败:password_reset_tokens表已定义多个主键
Laravel生产环境迁移报错:多个主键已定义
报错信息
Illuminate\Database\QueryException SQLSTATE[42000]: Syntax error or access violation: 1068 Multiple primary key defined (Connection: mysql, SQL: alter table `password_reset_tokens` add primary key (`email`)) at vendor/laravel/framework/src/Illuminate/Database/Connection.php:795 791▕ // If an exception occurs when attempting to run a query, we'll format the error 792▕ // message to include the bindings with SQL, which will make this exception a 793▕ // lot more helpful to the developer instead of just the database's errors. 794▕ catch (Exception $e) { ➜ 795▕ throw new QueryException( 796▕ $this->getName(), $query, $this->prepareBindings($bindings), $e 797▕ ); 798▕ } 799▕ } +9 vendor frames 10 database/migrations/2014_10_12_100000_create_password_reset_tokens_table.php:14 Illuminate\Support\Facades\Facade::__callStatic("create") +24 vendor frames 35 artisan:35 Illuminate\Foundation\Console\Kernel::handle(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
迁移代码
return new class extends Migration { /** * Run the migrations. */ public function up(): void { Schema::create('password_reset_tokens', function (Blueprint $table) { $table->string('email')->primary(); $table->string('token'); $table->timestamp('created_at')->nullable(); }); } /** * Reverse the migrations. */ public function down(): void { Schema::dropIfExists('password_reset_tokens'); } };
问题原因
password_reset_tokens表已经存在于生产数据库中,且该表已设置主键。当前迁移尝试再次创建该表并将email设为主键,触发数据库的主键冲突校验,导致报错。
解决步骤
1. 确认表是否存在
登录生产环境MySQL数据库,执行以下命令检查表状态:
SHOW TABLES LIKE 'password_reset_tokens';
2. 根据表的实际情况处理
情况一:表已存在且结构符合要求
直接标记该迁移为已执行,避免重复运行。在migrations表中插入记录:
INSERT INTO migrations (migration, batch) VALUES ('2014_10_12_100000_create_password_reset_tokens_table', (SELECT MAX(batch) + 1 FROM migrations));
执行后用php artisan migrate:status确认该迁移已标记为完成。
情况二:表已存在但结构不符合预期
- 先备份表数据:
mysqldump -u [数据库用户名] -p [数据库名] password_reset_tokens > password_reset_backup.sql
- 删除现有表:
DROP TABLE password_reset_tokens;
- 重新执行迁移:
php artisan migrate --force
3. 后续预防措施
- 执行迁移前,先用
php artisan migrate:status查看已完成的迁移列表,避免重复执行。 - 生产环境执行迁移必须加
--force参数跳过交互确认,但执行前要仔细核对迁移内容,防止数据丢失。
内容的提问来源于stack exchange,提问作者Alphy Gacheru
相关产品推荐
相关产品推荐

