CakePHP - get last query run

前端 未结 11 508
萌比男神i
萌比男神i 2020-12-02 13:33

I want to get the last query CakePHP ran. I can\'t turn debug on in core.php and I can\'t run the code locally. I need a way to get the last sql query and log it to the erro

相关标签:
11条回答
  • 2020-12-02 13:36

    You can use this:

    $log = $this->Model->getDataSource()->getLog(false, false);
    
    pr($log);die;
    
    0 讨论(0)
  • 2020-12-02 13:38

    Combination of Matt's and blavia's solution (works when debug is not 2):

    $dbo = $this->Model->getDatasource();
    $oldStateFullDebug = $dbo->fullDebug;
    $dbo->fullDebug = true;
    // find or whatever...
    $this->Model->find("all");
    $logs = $dbo->getLog();
    $lastLog = end($logs['log']);
    CakeLog::write("DBLog", $lastLog['query']);
    $dbo->fullDebug = $oldStateFullDebug;
    
    0 讨论(0)
  • 2020-12-02 13:45

    Simple you can use showLog() function

    var_dump($this->YourModel->getDataSource()->showLog());
    
    0 讨论(0)
  • 2020-12-02 13:45

    This is a very late answer, i know, but for whoever needs this in the future, you can always restrict setting debug to your IP, For example:

    Configure::write('debug', 0);
    if($_SERVER["REMOTE_ADDR"] == '192.168.0.100'){
    Configure::write('debug', 2); //Enables debugging only for your IP.
    }
    
    0 讨论(0)
  • 2020-12-02 13:46

    Tested in CakePHP v2.3.2

    $log = $this->Model->getDataSource()->getLog(false, false);
    debug($log);
    
    0 讨论(0)
  • 2020-12-02 13:50

    You can use this inline.

    $dbo = $this->Model->getDatasource();
    // store old state
    $oldStateFullDebug = $dbo->fullDebug;
    // turn fullDebug on
    $dbo->fullDebug = true;
    
    // Your code here! eg.
    $this->Model->find('all');
    
    // write to logfile
    // use print_r with second argument to return a dump of the array
    Debugger::log(print_r($dbo->_queriesLog, true));
    // restore fullDebug
    $dbo->fullDebug = $oldStateFullDebug;
    
    0 讨论(0)
提交回复
热议问题