How to get the last query executed by Cakephp?

Asked

Viewed 359 times

4

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 getLastQuery is only executed when debug is set to 2 would like to achieve with the value set to 0

  • 1

    It only works with debug enabled, because it uses the cake debug log, as far as I know, I would need to implement something like this directly in the lib model.

  • Apparently its function is OK, but this works -<? php end($this->Modelname->getDataSource()->getLog()['log'])['query']? >, whereas you are running this code in the controller.

1 answer

1


Try it like 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 reply from Soen:https://stackoverflow.com/questions/14981941/echo-this-elementsql-dump-without-debug-and-in-a-mail

Browser other questions tagged

You are not signed in. Login or sign up in order to post.