Getting raw sql in Yii2

I have a request:

$popular = self::find()
    ->from(self::tableName() . ' as t')
    ->with('user');

      

When I try to print sql:

$popular->createCommand()->rawSql

      

This gives me:

SELECT * FROM "themes" "t"

      

So, I can get the complete raw query with "join":

SELECT * FROM "themes" "t" LEFT JOIN "users" u ON u.user_id = t.author_id

      

+3


source to share


2 answers


He has already answered here .

You can var_dump

generate SQL for instances ActiveQuery

like this:

var_dump($query->prepare(Yii::$app->db->queryBuilder)->createCommand()->rawSql);

      



However, I recommend using the inline debug model and panel.

PS . As for your specific request - with()

doesn't do it JOIN

, instead it does additional requests and populates the relationship attributes with the actual related records. To use JOIN

you need to explicitly specify it, for example with joinWith()

.

+3


source


Hope this helps



$query = new Query;

$query  ->select(['themes.c1 AS d1', 'themes.c2 As d2..'])

        ->from('themes')

        ->leftJoin('users', 'users.user_id = themes.author_id');

$command = $query->createCommand();

$data = $command->queryAll();

      

0


source







All Articles