Symfony 6自定义Command执行SQL文件报SQLSTATE[42000]错误求助
解决Symfony自定义Command导入SQL文件的问题
你遇到的核心问题是:终端里的$(< ./sql/zones.sql)是Bash的命令替换语法,它会自动读取文件内容并作为参数传给doctrine:query:sql;但Symfony的Command调用逻辑不会解析Bash语法,直接传这个字符串会被当作SQL语句本身,自然触发SQL语法错误。
正确实现方案
不要依赖Bash的语法,在自定义Command里先读取SQL文件内容,再将内容作为参数传给doctrine:query:sql命令,同时用Symfony自带的项目根目录方法避免路径问题。
自定义Command代码示例
<?php namespace App\Command; use Symfony\Component\Console\Attribute\AsCommand; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Application; use Symfony\Component\Console\Tester\CommandTester; #[AsCommand( name: 'app:import-sql', description: '导入SQL文件到数据库', )] class ImportSqlCommand extends Command { private string $projectDir; public function __construct(string $projectDir) { $this->projectDir = $projectDir; parent::__construct(); } protected function execute(InputInterface $input, OutputInterface $output): int { // 从项目根目录拼接SQL文件绝对路径,避免相对路径混乱 $sqlFilePath = $this->projectDir . '/sql/zones.sql'; // 检查文件是否存在 if (!file_exists($sqlFilePath)) { $output->writeln("<error>未找到SQL文件:$sqlFilePath</error>"); return Command::FAILURE; } // 读取SQL文件内容 $sqlContent = file_get_contents($sqlFilePath); if ($sqlContent === false) { $output->writeln("<error>读取SQL文件失败:$sqlFilePath</error>"); return Command::FAILURE; } // 调用Doctrine的query:sql命令并传入读取到的SQL内容 $application = new Application($this->getApplication()->getKernel()); $doctrineCommand = $application->find('doctrine:query:sql'); $commandTester = new CommandTester($doctrineCommand); $commandTester->execute( ['sql' => $sqlContent], ['verbosity' => $output->getVerbosity()] ); // 输出Doctrine命令的执行结果 $output->writeln($commandTester->getDisplay()); return Command::SUCCESS; } }
关键说明
- 路径问题解决:通过注入的
$projectDir(Symfony自动提供项目根目录路径)拼接SQL文件路径,彻底避免相对路径导致的文件找不到问题。 - 替换Bash语法:手动读取文件内容,再将内容作为参数传给Doctrine命令,效果和终端执行
php bin/console doctrine:query:sql "$(< ./sql/zones.sql)"完全一致。 - 兼容性:不依赖Bash环境,跨Windows、Linux、Mac平台都能正常运行。
内容的提问来源于stack exchange,提问作者Ludneo
相关产品推荐
相关产品推荐

