Home Getting a raw SQL query with variables in Yii1
Reply: 2

Getting a raw SQL query with variables in Yii1

Alexander Yukal
1#
Alexander Yukal Published in 2018-02-14 18:06:55Z

Is Yii1 has any native methods to get the raw SQL with variables built?

I try to get a complex query built on a few subqueries using CDbExpression and CommandBuilder. I got this as a result:

SELECT * FROM `news` `t` WHERE id IN (:ycp0, :ycp1, :ycp2, :ycp3, :ycp4) LIMIT 5

The dump of the criteria content:

CDbCriteria Object (
  [select] => *
  [condition] => id IN (:ycp0, :ycp1, :ycp2, :ycp3, :ycp4)

  ...

  [params] => Array(
    [:ycp0] => CDbExpression Object(
      [expression] => SELECT id FROM `news` `t` WHERE (rubric=:rb1) AND (:im2 & `im`=:im2) LIMIT 1
      [params] => Array(
        [:rb1] => 1
        [:im2] => 2
      )
    )

    ...

  )
)

I expected for compiled query string like this:

SELECT * FROM .. WHERE id IN(
    (SELECT id FROM .. WHERE .. ORDER BY .. LIMIT 1),
    (SELECT id FROM .. WHERE .. ORDER BY .. LIMIT 1)
) ORDER BY .. LIMIT 5

This is what I do in my code

$criteria = new CDbCriteria( ... );
$sql = $this->commandBuilder->createFindCommand($tableName, $criteria)->getText();
$queries[] = new CDbExpression($sql, $criteria->params);

Then I try to combine subqueries to one complex query

$criteria = new CDbCriteria( ... );
$criteria->addInCondition('id', $queries);

And finally, I try to get the result as SQL-query

$sql = $this->commandBuilder->createFindCommand($tableName, $criteria)->getText();
Ketan Vekariya
2#
Ketan Vekariya Reply to 2018-02-14 19:19:10Z

There are few other options to perform the same thing but i will suggest you should use the following

$results = MyModel::model()->findAllBySql("...");

Or you can prefer the following : Sub-queries ActiveRecord Yii

ldg
3#
ldg Reply to 2018-02-15 00:53:45Z

You can use enableParamLogging in your db config (boolean). You can set it up so it's used conditionally -- make sure to not use it in production.

    'db' => [
        'connectionString' => 'mysql:host=' . $dbhost . ';port=' . $dbport . ';dbname=' . $dbname,
        'emulatePrepare' => true,
        'username' => $db_user,
        'password' => $db_pass,
        'schemaCachingDuration' => 3600,
        'charset' => 'utf8',
        'enableProfiling' => $db_profile,
        'enableParamLogging' => $db_params,
    ],

Then you can add 'class'=>'CWebLogRoute' to your log routes if you want to see all the output in your browser. docs

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.315754 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO