Phalcon 框架如何在model执行完毕,如何打印SQL?

Phalcon 框架如何在model执行完毕,如何打印SQL?

 $where = [

                'conditions' => "stat_date BETWEEN :start_stat_date: AND :end_stat_date:",
                'bind'       => [
                    'start_stat_date' =>date('Y-m-d', strtotime('-1 day')),
                    'end_stat_date' => date('Y-m-d', strtotime('-7 day')),
                ],

                'columns'=>'sum(day_reg_act_parent_num) AS count',
            ];

      $user  = $model->findFirst($where);
      
      如何打印出上面语句最后构造成的SQL呢?
阅读 9.1k
1 个回答

在DI注册DB服务的时候,执行SQL监听事件:

use Phalcon\Db\Profiler as DbProfiler;
use Phalcon\Mvc\Model\Manager as ModelsManager;

$di -> setShared('db', function () use($config) {
    $dbconfig = $config -> database -> db;
    $dbconfig = $dbconfig -> toArray();
    if (!is_array($dbconfig) || count($dbconfig)==0) {
        throw new \Exception("the database config is error");
    }
    $eventsManager = new \Phalcon\Events\Manager();
    // 分析底层sql性能,并记录日志
    $profiler = new DbProfiler();
    $eventsManager -> attach('db', function ($event, $connection) use ($profiler) {
        if($event -> getType() == 'beforeQuery'){
            //在sql发送到数据库前启动分析
            $profiler -> startProfile($connection -> getSQLStatement());
        }
        if($event -> getType() == 'afterQuery'){
            //在sql执行完毕后停止分析
            $profiler -> stopProfile();
            //获取分析结果
            $profile = $profiler -> getLastProfile();
            $sql = $profile->getSQLStatement();
            $executeTime = $profile->getTotalElapsedSeconds();
            //日志记录
            $logger = \Marser\App\Core\PhalBaseLogger::getInstance();
            $logger -> write_log("{$sql} {$executeTime}", 'debug');
        }
    });
    $connection = new \Phalcon\Db\Adapter\Pdo\Mysql(array(
        "host" => $dbconfig['host'], "port" => $dbconfig['port'],
        "username" => $dbconfig['username'],
        "password" => $dbconfig['password'],
        "dbname" => $dbconfig['dbname'],
        "charset" => $dbconfig['charset'])
    );
    /* 注册监听事件 */
    $connection->setEventsManager($eventsManager);
    return $connection;
});

具体参考PhalconCMS的代码:https://github.com/KevinJay/P...

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进