Laravel如何设置指定表不被php artisan migrate:fresh命令删除
Laravel 执行
migrate:fresh 时跳过指定大表的配置方案 migrate:fresh 命令的默认逻辑是直接枚举数据库内所有表并全部删除,再重跑所有迁移,你可以根据自己的使用场景选择以下方案:
方案1:修改迁移逻辑,配合自定义命令(适合长期使用)
这是最稳定的方案,适配所有Laravel版本:
- 首先在
app/Providers/AppServiceProvider.php的boot方法中添加自定义删表逻辑,指定要排除的大表:
<?php namespace App\Providers; use Illuminate\Support\Facades\DB; use Illuminate\Database\Schema\Builder; use Illuminate\Support\ServiceProvider; class AppServiceProvider extends ServiceProvider { public function boot() { // 自定义删表方法,支持排除指定表 Builder::macro('dropAllTablesExcept', function (array $exceptTables = []) { // 关闭外键约束避免删表报错 DB::statement('SET FOREIGN_KEY_CHECKS = 0'); // 获取所有表名,过滤需要排除的表 $allTables = collect(DB::select('SHOW TABLES')) ->map(fn ($item) => current((array) $item)) ->filter(fn ($tableName) => !in_array($tableName, $exceptTables)); // 批量删除不需要排除的表 $allTables->each(fn ($table) => DB::statement("DROP TABLE IF EXISTS `{$table}`")); // 恢复外键约束 DB::statement('SET FOREIGN_KEY_CHECKS = 1'); }); } }
- 生成自定义的migrate命令:
php artisan make:command MigrateFreshExcept
- 编辑生成的命令文件
app/Console/Commands/MigrateFreshExcept.php:
<?php namespace App\Console\Commands; use Illuminate\Console\Command; use Illuminate\Support\Facades\Schema; class MigrateFreshExcept extends Command { protected $signature = 'migrate:fresh-except {--except=* : 要排除的表名,多个用空格分隔}'; protected $description = '执行migrate:fresh,排除指定的表不删除'; public function handle() { $except = $this->option('except') ?: ['你要保留的大表名']; // 这里可以写默认要排除的表 Schema::dropAllTablesExcept($except); $this->call('migrate'); $this->info('迁移执行完成,指定表已保留'); } }
- 之后需要刷新迁移的时候,直接执行以下命令即可,不会删除你指定的大表:
php artisan migrate:fresh-except # 如果需要临时排除其他表,也可以传参: # php artisan migrate:fresh-except --except=表1 --except=表2
方案2:调整迁移路径(适合临时使用、不想改核心代码的场景)
- 把你要保留的大表对应的迁移文件,单独移动到一个独立目录,比如
database/migrations/protected - 执行
migrate:fresh的时候指定只跑其他迁移的路径,同时配合在大表迁移的up方法开头加存在判断,避免重复建表报错:
// 大表对应的迁移文件的up方法 public function up() { if (Schema::hasTable('你的大表名')) { return; } // 原本的建表逻辑 }
- 执行刷新命令:
php artisan migrate:fresh --path=database/migrations/default
注意事项
如果你保留的大表有依赖的外键关联其他表,需要提前处理好外键约束,避免其他表删除时报错。
内容的提问来源于stack exchange,提问作者Stephan Salley
相关产品推荐
相关产品推荐

