yii2 获取 最后执行 sql 的三种方法

PHP 投稿 111100 0 评论

yii2 获取 最后执行 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拉,在这里打断点输出即可。

编程笔记 » yii2 获取 最后执行 sql 的三种方法

赞同 (72) or 分享 (0)
游客 发表我的评论   换个身份
取消评论

表情
(0)个小伙伴在吐槽