Last active
July 9, 2019 09:40
-
-
Save daum/6dba57f690aff49b60535ba3a723d411 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Example\Doctrine\Util; | |
use Doctrine\ORM\Query; | |
class QueryUtils | |
{ | |
/** | |
* @param Query $query | |
* @return array An array with 3 indexes, sql the SQL statement with parameters as ?, params the ordered parameters, and paramTypes as the types each parameter is. | |
*/ | |
public static function getRunnableQueryAndParametersForQuery(Query $query) | |
{ | |
$sql = $query->getSQL(); | |
$c = new \ReflectionClass('Doctrine\ORM\Query'); | |
$parser = $c->getProperty('_parserResult'); | |
$parser->setAccessible(true); | |
/** @var \Doctrine\ORM\Query\ParserResult $parser */ | |
$parser = $parser->getValue($query); | |
$resultSet = $parser->getResultSetMapping(); | |
// Change the aliases back to what was originally specified in the QueryBuilder. | |
$sql = preg_replace_callback('/AS\s([a-zA-Z0-9_]+)/',function($matches) use($resultSet) { | |
$ret = 'AS '; | |
if($resultSet->isScalarResult($matches[1])) | |
$ret.=$resultSet->getScalarAlias($matches[1]); | |
else | |
$ret.=$matches[1]; | |
return $ret; | |
},$sql); | |
$m = $c->getMethod('processParameterMappings'); | |
$m->setAccessible(true); | |
list($params,$types)= $m->invoke($query,$parser->getParameterMappings()); | |
return ['sql' => $sql, 'params' => $params,'paramTypes' => $types]; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Example Usage | |
// Get a Query Builder | |
$qb = $this->getDoctrine() | |
->getRepository('AppBundle:Example') | |
->getQueryBuilderForParams($params); | |
$queryInfo = QueryUtils::getRunnableQueryAndParametersForQuery($qb->getQuery()); | |
// Use the query to insert to a temp table. | |
$this->getDoctrine() | |
->getManager('default') | |
->getConnection() | |
->executeQuery("INSERT INTO my_temp_table (col1,col2,col3,col4) ".$queryInfo['sql'], | |
$queryInfo['params'], | |
$queryInfo['paramTypes']); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment