CakePHP - get last query run

2019-01-16 11:06发布

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 error log without effecting the live site. This query is failing but is being run.

something like this would be great:

$this->log($this->ModelName->lastQuery);

Thanks in advance.

9条回答
迷人小祖宗
2楼-- · 2019-01-16 11:55

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);
}
查看更多
Summer. ? 凉城
3楼-- · 2019-01-16 11:58

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;
查看更多
Summer. ? 凉城
4楼-- · 2019-01-16 11:58

Simple you can use showLog() function

var_dump($this->YourModel->getDataSource()->showLog());
查看更多
登录 后发表回答