如何调试MySQL/Doctrine2查询?

2022-08-30 15:22:19

我正在将MySQL与Zend Framework & Doctrine 2一起使用。我认为即使你不使用教义2,你也会熟悉这样的错误。

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'ASC' at line 1

问题是我没有看到完整的查询。如果没有ORM框架,我可能可以很容易地回显sql,但是有了框架,我怎么能找出它试图执行的SQL呢?我将误差缩小到

$progress = $task->getProgress();

$progress已声明

// Application\Models\Task
/**
 * @OneToMany(targetEntity="TaskProgress", mappedBy="task")
 * @OrderBy({"seq" = "ASC"})
 */
protected $progress;

在MySQL中,任务类看起来像

CREATE TABLE `tasks` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `owner_id` int(11) DEFAULT NULL,
  `assigned_id` int(11) DEFAULT NULL,
  `list_id` int(11) DEFAULT NULL,
  `name` varchar(60) NOT NULL,
  `seq` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `tasks_owner_id_idx` (`owner_id`),
  KEY `tasks_assigned_id_idx` (`assigned_id`),
  KEY `tasks_list_id_idx` (`list_id`),
  CONSTRAINT `tasks_ibfk_1` FOREIGN KEY (`owner_id`) REFERENCES `users` (`id`),
  CONSTRAINT `tasks_ibfk_2` FOREIGN KEY (`assigned_id`) REFERENCES `users` (`id`),
  CONSTRAINT `tasks_ibfk_3` FOREIGN KEY (`list_id`) REFERENCES `lists` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1$$

答案 1

在学说 2 中调试查询的最简单解决方案:

$em->getConnection()
  ->getConfiguration()
  ->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger())
;

答案 2

你必须使用 DBAL SQLLogger。您可以使用基本的本机 SQL Logger \Doctrine\DBAL\Logging\EchoSQLLogger,也可以使用 Doctrine\DBAL\Logging\SQLLogger 接口实现您的应用程序。

对于基本记录器,必须将 SQL 记录器附加到实体管理器。因此,在您的 Doctrine 引导程序文件中,请使用:

$config = new Doctrine\ORM\Configuration ();
// ... config stuff
$config->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger());
$connectionParams = array(
        'dbname' => 'example',
        'user' => 'example',
        'password' => 'example',
        'host' => 'localhost',
        'driver' => 'pdo_mysql');
//make the connection through an Array of params ($connectionParams)
$em = EntityManager::create($connectionParams, $config);

请注意,我们从$connectionParams数组创建实体管理器。

重要提示:.如果使用 DBAL 连接来创建实体管理器,则必须在 DBAL 连接和 ORM 实体管理器中附加它。例如,在Zend Framework中,

您执行此操作:

$config = new Doctrine\ORM\Configuration ();
// ...config stuff
// LOGGER
$config->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger());

// make the connection through DBAL (DriverManager::getConnection)
// note that we attach $config in $connApp(DBAL) and $emApp(ORM)
$connApp = DriverManager::getConnection($connectionParams, $config);
$emApp = EntityManager::create($connApp, $config);
Zend_Registry::set('emApp', $emApp);
Zend_Registry::set('connApp', $connApp);

推荐