Skip to main content

获取 最后执行的sql

一、使用getRawSql方法
$query = Sfjvip::find();
$query->select(['username','age'])->where(['id'=>1)->one();
 
echo $query->createCommand()->getRawSql();//输出sql语句
二、开启debug模块,在DB那一栏里面有的sql信息。
三、改Yii源码
比如 Sfjvip::updateAll 方法,通过phpstorm编辑器定位到updateAll方法的源代码:
public static function updateAll($attributes, $condition = '', $params = [])
{
   $command = static::getDb()->createCommand();
   $command->update(static::tableName(), $attributes, $condition, $params);
 
   return $command->execute();
}
继续定位execute方法:
public function execute()
{
   $sql = $this->getSql();
   $rawSql = $this->getRawSql();
 
   Yii::info($rawSql, __METHOD__);
   if ($sql == '') {
      return 0;
   }
 
   $this->prepare(false);
        $token = $rawSql;
        try {
            Yii::beginProfile($token, __METHOD__);
 
            $this->pdoStatement->execute();
            $n = $this->pdoStatement->rowCount();
 
            Yii::endProfile($token, __METHOD__);
 
            $this->refreshTableSchema();
 
            return $n;
        } catch (\Exception $e) {
            Yii::endProfile($token, __METHOD__);
            throw $this->db->getSchema()->convertException($e, $rawSql);
        }
    }
方法里 $rawSql就是最原生要执行的sql拉,在这里打断点输出即可。

来自 <https://www.sfjvip.com/php/2514.html>