19

I want to print query:

$demo = Demo::find()->all();

I want to see converted SQL query with parameters:

createCommand()->getRawSql();

is showing me an error message:

yii2 Call to a member function createCommand() on a non-object

Please help me to see the actual SQL query.

krlzlx
  • 5,752
  • 14
  • 47
  • 55
Paritosh Mahale
  • 1,238
  • 2
  • 14
  • 42

6 Answers6

39

Eg:

$query = Demo::find()->where(['category'=>2]);
echo $query->createCommand()->getRawSql();
Ngô Văn Thao
  • 3,671
  • 1
  • 20
  • 24
6
$demo = Demo::find()->all();

returns an array of all models not the actual sql.

if you want the sql use this (this is the sql which is excecuted)

$query = Demo::find()->where('1');
var_dump($query->prepare(Yii::$app->db->queryBuilder)->createCommand()->rawSql)
BHoft
  • 1,663
  • 11
  • 18
5

A simple way is use the Active Query Builder createCommand method

  $sqlCommand = Demo::find()->createCommand();

  echo $sqlCommand->sql;

see this for refernce http://www.yiiframework.com/doc-2.0/yii-db-activequery.html and http://www.yiiframework.com/doc-2.0/yii-db-activequery.html#createCommand()-detail

ScaisEdge
  • 131,976
  • 10
  • 91
  • 107
  • it showing me an error message "Call to a member function createCommand() on a non-object" – Paritosh Mahale Nov 10 '16 at 07:54
  • Be sure that Demo::Find() is a valid object .. and you have access .. eventually update your question and show your code .. where use are using this statements – ScaisEdge Nov 10 '16 at 08:09
  • yes, Demo::find()->all(); returns an array of object . and i am using this query in method of model class – Paritosh Mahale Nov 10 '16 at 08:30
  • You don't should use Demo::find()->all(); but Demo::find()->createCommand(); .. you must substitute all() with createComman() if you want see the resulting query .. Demo::find()->all(); return the row model objec not the sql intruction for retrieve this rows – ScaisEdge Nov 10 '16 at 08:34
2

Hiii Paritosh,
You can view the query that is being executed in SQl format by yii\db\Connection::createCommand() objects like

$query = new \yii\db\Query;
        $query->select(['*'])
                ->from('table_demo');

        $command = $query->createCommand();

//      $command->sql returns the actual SQL
        $rows = $command->sql;
        echo $rows;
        exit;
Mohan
  • 606
  • 4
  • 11
0

Easiest way is to select some non-existing field, for example:

Demo::find()->select('nonExistingField')->all();

and see the debug message like this:

The SQL being executed was: SELECT `nonExistingField` ...

This way, you dont need to remove your ->all() or ->one() calls.

TomoMiha
  • 1,218
  • 1
  • 14
  • 12
0

The shortest way is probably:

echo Demo::find()->createCommand()->rawSql;
WeSee
  • 3,158
  • 2
  • 30
  • 58