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.

2
  • 2
    This question already been answered <stackoverflow.com/questions/27389146/…> Commented Nov 10, 2016 at 7:54
  • 1
    No the the queston and the asnwer in the link is not related to this question .. Commented Nov 10, 2016 at 10:44

6 Answers 6

40

Eg:

$query = Demo::find()->where(['category'=>2]);
echo $query->createCommand()->getRawSql();
Sign up to request clarification or add additional context in comments.

Comments

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)

Comments

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

4 Comments

it showing me an error message "Call to a member function createCommand() on a non-object"
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
yes, Demo::find()->all(); returns an array of object . and i am using this query in method of model class
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
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;

Comments

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.

Comments

0

The shortest way is probably:

echo Demo::find()->createCommand()->rawSql;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.