CakePHP - get last query run

前端 未结 11 509
萌比男神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:50

    There are two methods to view the query in CakePHP.

    Both methods you have to add the below one line in app/Config/core.php

    Configure::write('debug', 2); 
    

    First methods :

    debug($this->getLastQuery()); 
    

    where you want to get the query add above line and call this function getLastQuery() on same controller using below code

    public function getLastQuery() {
        $dbo = $this->TModel->getDatasource();  //Here TModel is a model.what table you want to print 
        $logs = $dbo->getLog();
        $lastLog = end($logs['log']);
        return $lastLog['query'];
    }
    

    second method :

    add the below line in the any Elements files.

    <?php echo $this->element('sql_dump'); ?>
    
    0 讨论(0)
  • 2020-12-02 13:51

    In CakePHP 1.x, the data you want is accessible in DataSource::_queriesLog. Cake doesn't really provide a getter method for this member, but the underlying language being PHP, nothing stops you from doing the following:

    In app/app_model.php:

    function getLastQuery()
    {
        $dbo = $this->getDatasource();
        $logs = $dbo->_queriesLog;
    
        return end($logs);
    }
    
    0 讨论(0)
  • 2020-12-02 13:52

    This will help you.

    echo '<pre>';
    $log = $this->YOUR_MODEL->getDataSource(); 
    print_r($log);
    exit;
    
    0 讨论(0)
  • 2020-12-02 13:55

    For Cake 2.0, the query log is protected so this will work

    function getLastQuery() {
      $dbo = $this->getDatasource();
      $logs = $dbo->getLog();
      $lastLog = end($logs['log']);
      return $lastLog['query'];
    }
    
    0 讨论(0)
  • 2020-12-02 13:55

    Having a quick skim of the book, cakephp api getLog you could turn on logTransaction. Although having not used it, I'm not sure how it will perform.

    Otherwise you could experiment with FirePHP and here is the a guide for it,

    You might try DebugKit, although off the top of my head I think you do still need debug 2 to get it to work.

    Hopefully something might give you a lead. :)

    0 讨论(0)
提交回复
热议问题