TP6.0.16数据库迁移需更换为think-migration:^3.0扩展,手动注册命令、重置migration文件路径至database/migrations/,统一使用php think migrate:create生成文件,重写类继承think\migration\Migrator,并确保database.php配置正确且小写type。

ThinkPHP 5.0 升级到 6.0.16 后,数据库迁移不能直接沿用原有方式——TP5 的迁移机制(如 think-migration:2.x)与 TP6.0.16 不兼容,且 TP6 官方不内置迁移功能,必须切换为适配 TP6 的迁移方案。核心在于更换扩展、重置元数据、规范文件路径与类结构,并处理配置加载差异。
确认并替换迁移扩展版本
TP5.0 常用 topthink/think-migration:^2.0(基于 Phinx 0.8),但该版本不支持 PHP 8.1+,且与 TP6.0.16 的命令注册机制、自动加载路径冲突。必须升级为 TP6 兼容版本:
- 执行
composer remove topthink/think-migration清理旧包 - 安装适配 TP6.0.x 的稳定版:
composer require topthink/think-migration:^3.0(注意:TP6.0.8+ 推荐 ^3.0;若项目已升至 TP6.1+ 或 TP8,则需 ^4.0) - 检查
vendor/topthink/think-migration/src/Command.php是否存在,确认类已正确加载
手动注册迁移命令并初始化元数据表
TP6.0.16 默认不自动注册迁移命令,漏掉这步会导致 php think migrate:install 报 “Command not defined”:
- 打开
app/command.php(或config/console.php,依项目结构而定),在'commands'数组中添加:'\think\migration\Command::class' - 运行
php think migrate:install创建think_migrations表(默认名,可改) - ⚠️ 若此前 TP5 迁移使用过
phinxlog表,需手动清空或重命名,避免与新think_migrations冲突
迁移文件路径与命名必须严格重置
TP5 的迁移文件常放在 database/migrate/ 或自定义路径,TP6.0.16 要求统一且不可配置:
立即学习“PHP免费学习笔记(深入)”;
- 将所有旧迁移文件移出原位置,新建标准目录:
database/migrations/ - 不再支持手写时间戳文件名,必须用命令生成:
php think migrate:create RebuildUsersTable - 生成的文件如
20261020210000_rebuild_users_table.php,类名须为RebuildUsersTable,继承think\migration\Migrator - 旧 TP5 迁移类若继承
Phinx\Migration\AbstractMigration,需全部重写为 TP6 格式,up()/down()中禁用模型和 Db 门面
适配数据库配置与执行逻辑
TP6.0.16 的数据库连接读取逻辑与 TP5 不同,迁移命令默认使用 config/database.php 中的 default 连接,且不读取 .env 中的 DB 配置:
- 检查
config/database.php中'type' => 'mysql'(小写!大写会报 Driver not supported) - 确保
'hostname'、'username'、'password'等字段填写正确,无空格或注释干扰 - 执行前先验证:
php think migrate:status查看待执行列表;首次运行用php think migrate:run,勿用php think migrate(无效命令) - 生产环境务必先在测试库回滚验证:
php think migrate:rollback --step=1,确认down()逻辑健壮(例如加字段后删字段,需先判断字段是否存在)



















