Print out a SQL single query (Yii 1.x)
Asked Answered
D

2

5

I have a massive query that is generated using CDbCriteria as shown below:-

$schema = Yii::app()->db->schema;
$builder = $schema->commandBuilder;

// how to echo out this query?
$command = $builder->createFindCommand($schema->getTable('myuser'), $criteria);
$results = $command->queryAll();

I know I can use the 'logging' feature of Yii to view the query, is it possible to just echo out this single query (as opposed to having Yii show me tons of other queries that are being run on the page).

Demott answered 26/10, 2015 at 11:7 Comment(1)
The easiest way I've found for this is to put a typo in the sql, it throws an error and all the sql is on the screen!Tauten
P
6

you can print query built by query builder by using $command->text. In your example code will be:

    $schema = Yii::app()->db->schema;
    $builder = $schema->commandBuilder;
    $criteria = new CDbCriteria();
    $command = $builder->createFindCommand($schema->getTable('name_of_table'), $criteria);
    $results = $command->text;
    echo $results;

$command->text will return your complete query text

Playground answered 26/10, 2015 at 11:19 Comment(2)
@Demott absolute pleasure :)Playground
if I add $criteria->with = ['relation']; in $command->text I can't see JOIN. How can I use with here?Mala
K
3

Add this in your config file. You can see the query and other details at the bottom of the page.

'db'=>array(
        'enableProfiling'=>true,
        'enableParamLogging' => true,
),
'log'=>array(
    'class'=>'CLogRouter',
    'routes'=>array(
        …
        array(
            'class'=>'CProfileLogRoute',
            'levels'=>'profile',
            'enabled'=>true,
        ),
    ),
),
Kimberliekimberlin answered 26/10, 2015 at 11:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.