How to print converted SQL query from yii2 query

2019-04-19 20:23发布

问题:

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.

回答1:

Eg:

$query = Demo::find()->where(['category'=>2]);
echo $query->createCommand()->getRawSql();


回答2:

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



回答3:

$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)


回答4:

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;


标签: yii2