How to print converted SQL query from yii2 query

2019-04-19 20:12发布

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.

标签: yii2
4条回答
\"骚年 ilove
2楼-- · 2019-04-19 20:24
$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)
查看更多
欢心
3楼-- · 2019-04-19 20:29

Eg:

$query = Demo::find()->where(['category'=>2]);
echo $query->createCommand()->getRawSql();
查看更多
兄弟一词,经得起流年.
4楼-- · 2019-04-19 20:36

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

查看更多
ゆ 、 Hurt°
5楼-- · 2019-04-19 20:44

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;
查看更多
登录 后发表回答