Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print converted SQL query from yii2 query

Tags:

yii2

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.

like image 711
Paritosh Mahale Avatar asked Nov 10 '16 07:11

Paritosh Mahale


People also ask

How to write SQL query in Yii2?

Call yii\db\QueryBuilder to generate a SQL statement based on the current construct of yii\db\Query; Create a yii\db\Command object with the generated SQL statement; Call a query method (e.g. queryAll()) of yii\db\Command to execute the SQL statement and retrieve the data.

How to write query in yii?

use createcommand() method: use yii\db\Query(); $connection = \Yii::$app->db; $query = new Query; $insql = $connection->createCommand("SELECT* FROM inventory ); $result=$insql->queryAll(); the above method list all data from the inventory table.

What is active query in Yii2?

An ActiveQuery can be a normal query or be used in a relational context. ActiveQuery instances are usually created by yii\db\ActiveRecord::find() and yii\db\ActiveRecord::findBySql(). Relational queries are created by yii\db\ActiveRecord::hasOne() and yii\db\ActiveRecord::hasMany().

Is null in Yii2 query?

Yii2 will use "IS NULL" if the $values === null , but in case the value is supplied as an array, and one of those array elements is null, it will not get any special treatment, resulting in the query never matching any records with NULL value.


2 Answers

Eg:

$query = Demo::find()->where(['category'=>2]);
echo $query->createCommand()->getRawSql();
like image 107
Ngô Văn Thao Avatar answered Sep 18 '22 12:09

Ngô Văn Thao


$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)
like image 40
BHoft Avatar answered Sep 18 '22 12:09

BHoft