Laravel项目迁移至MySQL时出现employee_id列不存在错误
Laravel迁移报错:ColumnDoesNotExist 解决办法
执行php artisan migrate时触发如下错误:
Migrating: 2022_02_25_173457_add_morph_columns_in_payment_accounts_table Doctrine\DBAL\Schema\Exception\ColumnDoesNotExist There is no column with name "employee_id" on table "payment_accounts". at vendor/doctrine/dbal/src/Schema/Exception/ColumnDoesNotExist.php:16 12▕ final class ColumnDoesNotExist extends SchemaException 13▕ { 14▕ public static function new(string $columnName, string $table): self 15▕ { ➜ 16▕ return new self( 17▕ sprintf('There is no column with name "%s" on table "%s".', $columnName, $table), 18▕ self::COLUMN_DOESNT_EXIST, 19▕ ); 20▕ } +9 vendor frames 10 database/migrations/2022_02_25_173457_add_morph_columns_in_payment_accounts_table.php:18 Illuminate\Database\Schema\Builder::table("payment_accounts", Object(Closure)) +22 vendor frames 33 artisan:35 Illuminate\Foundation\Console\Kernel::handle(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
解决步骤:
- 检查迁移文件:打开
database/migrations/2022_02_25_173457_add_morph_columns_in_payment_accounts_table.php,定位第18行代码,确认是否存在操作employee_id字段的逻辑(比如删除、修改该字段),而这个字段实际并未在payment_accounts表中创建。 - 核对数据库表结构:登录数据库直接查看
payment_accounts表的字段,确认employee_id是否真的不存在。 - 修正迁移逻辑:
- 如果是误加了操作
employee_id的代码,直接删除相关语句; - 如果该字段是后续操作必需的,先在当前迁移文件中添加
employee_id字段(比如$table->unsignedBigInteger('employee_id')->nullable();,根据业务需求调整字段类型),再执行morph字段的添加操作; - 如果是迁移顺序问题(创建
employee_id的迁移在当前迁移之后),调整迁移文件的时间戳,让创建字段的迁移优先执行,或者手动在数据库中添加该字段。
- 如果是误加了操作
- 重新执行迁移:修正后运行
php artisan migrate验证结果。 - 状态混乱时的处理:如果迁移状态异常,可执行
php artisan migrate:rollback回滚最近一次迁移后重新执行;开发环境下也可使用php artisan migrate:fresh重置所有迁移(注意:此操作会清空数据库所有数据)。
内容的提问来源于stack exchange,提问作者Abhishek singh
相关产品推荐
相关产品推荐

