Laravel 10批量重构DB::raw()为DB::raw()->getValue()的方案咨询
批量重构Laravel项目中
DB::raw()的方案 方法1:IDE全局正则替换
主流IDE(PhpStorm、VS Code)都支持正则批量替换,这是最快捷的方案:
- 打开全局替换功能(PhpStorm:
Ctrl+Shift+R;VS Code:Ctrl+Shift+H) - 开启正则匹配选项
- 查找内容:
DB::raw\((.*?)\) - 替换内容:
DB::raw($1)->getValue(DB::connection()->getQueryGrammar()) - 先选几个文件测试替换结果,确认无误后再全局执行
提示:如果
DB::raw()参数里有嵌套括号,改用这个正则适配复杂场景:DB::raw\(([^()]*(?:\([^()]*\)[^()]*)*)\)
方法2:自定义PHP脚本批量处理
如果IDE正则覆盖不了特殊场景,写个脚本遍历文件替换:
<?php // 在项目根目录执行此脚本 $targetDirs = [__DIR__ . '/app', __DIR__ . '/database']; // 按需添加要处理的目录 $fileExt = '.php'; foreach ($targetDirs as $dir) { $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir)); foreach ($iterator as $file) { if ($file->isFile() && $file->getExtension() === $fileExt) { $content = file_get_contents($file->getPathname()); $newContent = preg_replace('/DB::raw\((.*?)\)/', 'DB::raw($1)->getValue(DB::connection()->getQueryGrammar())', $content); if ($newContent !== $content) { file_put_contents($file->getPathname(), $newContent); echo "已更新: " . $file->getPathname() . PHP_EOL; } } } } echo "替换完成!";
- 执行前务必备份代码或提交Git,避免替换出错无法回滚
- 复杂嵌套场景同样需要调整正则表达式
方法3:修复Rector包的错误
如果坚持用Rector,先排查并解决错误:
- 更新到适配Laravel 10的版本:
composer require rector/rector-laravel --dev - 检查
rector.php配置,确保启用对应规则:
<?php use Rector\Laravel\Set\LaravelSetList; use Rector\Laravel\Rector\FuncCall\RawToDatabaseExpressionRector; use Rector\Config\RectorConfig; return static function (RectorConfig $rectorConfig): void { $rectorConfig->sets([LaravelSetList::LARAVEL_100]); $rectorConfig->rule(RawToDatabaseExpressionRector::class); };
- 先执行
vendor/bin/rector process app --dry-run做预检查,确认预期替换后再正式执行
内容的提问来源于stack exchange,提问作者reza Fallahi
相关产品推荐
相关产品推荐

