Yii2 Active Record to raw sql

1.5k views Asked by At

I would like to convert the active record query of yii2 to raw SQL equivalent to check if the query is working correctly or not.

It is easy to convert the Eloquent ORM of laravel to raw SQL using toSql() method

https://laravel.com/api/8.x/Illuminate/Database/Query/Builder.html#method_toSql

Is there any way to achieve this result in yii2, as I can only find the solutions from raw SQL to active record implementation.

If the question is still not clear will add the example for further explaination.

1

There are 1 answers

1
Raul Sauco On BEST ANSWER

Yes, you can use either the property sql or the method rawSql() of the query->command, for example:

$querySql = Model::find()->where(...)->createCommand()->sql;
$querySql = Model::find()->where(...)->createCommand()->getRawSql();

// Or, if you want to use the query somewhere else
$query = Model::find()->where(...);
...
$sql = $query->createCommand()->sql;

If you are just debugging, it is probably easier to see the query on the debug toolbar.