Doctrine - how to get the SQL INSERT query, in the postSave() event?

后端 未结 5 935
一向
一向 2021-02-09 05:57

I would like to get the exact SQL INSERT query that Doctrine generates when an object\'s save() method is called.

Preferably, I would like to get it in the postSave() ev

5条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-09 06:37

    you can use the profiler from the sfDoctrineDatabase class. Use the getQueryExecutionEvents to grab all queries.

    $databaseManager = sfContext::getInstance()->getDatabaseManager();
    if ($databaseManager) {
        foreach ($databaseManager->getNames() as $name) {
            $database = $databaseManager->getDatabase($name);
            if ($database instanceof sfDoctrineDatabase && $profiler = $database->getProfiler()) {
                foreach ($profiler->getQueryExecutionEvents() as $event) {
                    $conn = $event->getInvoker() instanceof Doctrine_Connection ? $event->getInvoker() : $event->getInvoker()->getConnection();
                    $params = sfDoctrineConnectionProfiler::fixParams($event->getParams());
                    $query = $event->getQuery() ;
    
                    foreach ($params as $param) {
                        $param = htmlspecialchars($param, ENT_QUOTES, sfConfig::get('sf_charset'));
                        $query = join(var_export(is_scalar($param) ? $param : (string) $param, true), explode('?', $query, 2));
                    }
                    // log the $query here, or use the symfony's logger
                    // sfContext::getInstance()->getLogger()->debug(sprintf('Query Run !! %s ', $query));
                }
            }
        }
    }
    

    dont forget to join the query with the parameters (so it will replace ? with the values )

    :D

提交回复
热议问题