Get raw sql from Phalcon query builder

Ian Bytchek picture Ian Bytchek · Jan 24, 2014 · Viewed 18.3k times · Source

Is it possible to extract raw sql query from the query builder instance in Phalcon? Something like this?

$queryBuilder = new Phalcon\Mvc\Model\Query\Builder();
$queryBuilder
    ->from(…)
    ->where(…);

$rawSql = $queryBuilder->hypotheticalGetRawQueryMethod();

Answer

Ian Bytchek picture Ian Bytchek · Jan 25, 2014

By error and trial the below seems to working. Would be great if someone could confirm if there's a better way.

$queryBuilder = new Builder();
$queryBuilder->from(…)->where(…);

$intermediate = $queryBuilder->getQuery()->parse();
$dialect      = DI::getDefault()->get('db')->getDialect();
$sql          = $dialect->select($intermediate);

Edit: As of 2.0.3 you can do it super simple, see comment for full details:

$modelsManager->createBuilder()
    ->from('Some\Robots')
    ->getQuery()
    ->getSql()