如何在 Composer 更新后自动运行数据库迁移(migrations)?

admin 百科 13
Composer 更新后自动运行数据库迁移需配置 scripts 钩子,推荐在 composer.json 中设置 post-update-cmd 和 post-install-cmd 为 "@php artisan migrate --force",并用 RUN_MIGRATIONS 环境变量控制启用,确保非交互式执行与生产安全。

如何在 Composer 更新后自动运行数据库迁移(migrations)?-第1张图片-佛山资讯网

Composer 更新后自动运行数据库迁移,核心是利用 Composer 的 scripts 机制,在 post-update-cmdpost-install-cmd 钩子中触发迁移命令。

配置 composer.json 的 scripts 钩子

在项目根目录的 composer.json 文件中,添加或修改 scripts 字段:

  • 确保 "post-update-cmd""post-install-cmd" 都指向你的迁移命令(例如 Laravel 的 php artisan migrate
  • 推荐写法(兼容安装和更新):

"scripts": {
  "post-update-cmd": [
    "@php artisan migrate --force"
  ],
  "post-install-cmd": [
    "@php artisan migrate --force"
  ]
}

登录后复制

注意:--force 是必需的(Laravel 6+ 要求),否则在非交互式环境(如 CI 或部署脚本)中迁移会中断。

避免重复迁移或生产环境误操作

直接在钩子里执行 migrate 有风险,尤其在多服务器部署或生产环境:

  • 迁移只应在一台机器上运行,否则可能并发冲突
  • 建议用环境变量控制是否启用自动迁移,例如:

"post-update-cmd": [
  "@php -r \"if (getenv('RUN_MIGRATIONS') === '1') exec('php artisan migrate --force');\""
]

登录后复制

然后通过 RUN_MIGRATIONS=1 composer update 显式开启,更安全可控。

标签: php laravel js json composer 工具 环境变量 red

发布评论 0条评论)

还木有评论哦,快来抢沙发吧~