Laravel数据库迁移失败:执行migrate:refresh --seed时报jobs表已存在
问题说明
执行命令 php artisan migrate:refresh --seed 时触发如下错误:
SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'jobs' already exists (Connection: mysql, SQL: create table
jobs(idbigint unsigned not null auto_increment primary key,titlevarchar(255) not null,descriptiontext not null,salaryint unsigned not null,locationvarchar(255) not null,categoryvarchar(255) not null,experienceenum('entry', 'intermediate', 'senior') not null,created_attimestamp null,updated_attimestamp null) default character set utf8mb4 collate 'utf8mb4_unicode_ci')
对应的jobs表迁移代码:
Schema::create('jobs', function (Blueprint $table) { $table->id(); $table->string('title'); $table->text('description'); $table->unsignedInteger('salary'); $table->string('location'); $table->string('category'); $table->enum('experience', ['entry', 'intermediate', 'senior']); $table->timestamps(); });
解决办法
办法1:手动删表后重新迁移
- 登录MySQL数据库,执行删表命令:
DROP TABLE IF EXISTS jobs;
- 重新执行迁移命令:
php artisan migrate:refresh --seed
办法2:修改迁移文件兼容已存在的表
如果使用Laravel 8.37及以上版本,可将Schema::create替换为Schema::createIfNotExists,让迁移自动跳过已存在的表:
Schema::createIfNotExists('jobs', function (Blueprint $table) { $table->id(); $table->string('title'); $table->text('description'); $table->unsignedInteger('salary'); $table->string('location'); $table->string('category'); $table->enum('experience', ['entry', 'intermediate', 'senior']); $table->timestamps(); });
修改后重新执行迁移命令即可。
办法3:清理迁移记录
检查migrations表,若存在该迁移的执行记录但表未被正确删除,手动删除对应记录:
DELETE FROM migrations WHERE migration LIKE '%create_jobs_table%';
之后运行:
php artisan migrate:refresh --seed
内容的提问来源于stack exchange,提问作者inta3

