How to get the last query executed by CakePHP?

Posted on

Question :

I want to get the last query executed by CakePHP

Example

$data  =  $this->Ticket->find('all',  array('conditions'  =>  $conditions,  'order'  =>  array('Ticket.id'  =>  'DESC')));

$this->query = $this->Ticket->getLastQuery();

public function getLastQuery($fromWhereClause = false){
        $dbo = $this->getDatasource();
        $logs = $dbo->getLog();
        $lastLog = end($logs['log']);
        if ($fromWhereClause) {
            return strstr($lastLog['query'], 'WHERE');
        }
        return $lastLog['query'];
}

but the getLastQuery is only executed when the debug is set to the value 2
I would like to get it set to 0

    

Answer :

Try this:

$data  =  $this->Ticket->find('all',  array('conditions'  =>  $conditions,  'order'  =>  array('Ticket.id'  =>  'DESC')));

$this->query = $this->Ticket->getLastQuery();

public function getLastQuery($fromWhereClause = false){
    $dbo = $this->getDatasource();
    $dbo->fullDebug = true;
    $logs = $dbo->getLog();
    $lastLog = end($logs['log']);
    if ($fromWhereClause) {
        return strstr($lastLog['query'], 'WHERE');
    }
    $dbo->fullDebug = false;
    return $lastLog['query'];
}

Based on this SOen response: link

    

Leave a Reply

Your email address will not be published. Required fields are marked *