在Yii1中获取带有变量的原始SQL查询

yvgpqqbh  于 2022-11-09  发布在  其他
关注(0)|答案(4)|浏览(205)

Yii 1是否有任何原生方法来获取带有变量的原始SQL?
我尝试使用CDbExpressionCommandBuilder在几个子查询上构建一个复杂的查询,结果如下:

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

标准内容的转储:

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
      )
    )

    ...

  )
)

我期望对这样的查询字符串进行编译:

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

这就是我在代码中所做的

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

然后,我尝试将子查询组合成一个复杂查询

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

最后,我尝试以SQL-query的形式获取结果

$sql = $this->commandBuilder->createFindCommand($tableName, $criteria)->getText();
f2uvfpb9

f2uvfpb91#

你可以在你的db config中使用enableParamLogging(布尔值),你可以设置它以便有条件地使用它--确保不在生产中使用它。

'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,
    ],

然后,如果您想在浏览器中查看所有输出,您可以将'class'=>'CWebLogRoute'添加到您的log路由中。docs

v6ylcynt

v6ylcynt2#

我想你要做这样的事情:$criteria = ...; $command = $builder->createFindCommand($schema->getTable('name_of_table'), $criteria); $results = $command->text;

ds97pgxw

ds97pgxw3#

您将获得带有params的SQL,就像

$sql = $this->commandBuilder->createFindCommand($tableName, $criteria)->getText();

然后获取用引号括起来的参数:

$params = array_map(function($param) { return '"' . $param . '"'; }, $criteria->params);

最后,替换配对:

echo strtr($sql, $params);
i34xakig

i34xakig4#

有几个其他选项来执行相同的事情,但我会建议您应该使用以下

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

或者,您可以选择以下选项:Sub-queries ActiveRecord Yii

相关问题