[英]How to get last run query in CakePHP 3.2?
我想在 CakePHP 3.2 中獲取最后執行的查詢,我之前在 CakePHP 2.x 中使用過以下內容:-
function getLastQuery() {
Configure::write('debug', 2);
$dbo = $this->getDatasource();
$logs = $dbo->getLog();
$lastLog = end($logs['log']);
$latQuery = $lastLog['query'];
echo "<pre>";
print_r($latQuery);
}
我如何在 CakePHP 3.x 中做到這一點?
簡單的英語:您需要做的就是修改config/app.php
找到Datasources
配置並設置'log' => true
'Datasources' => [
'default' => [
'className' => 'Cake\Database\Connection',
'driver' => 'Cake\Database\Driver\Mysql',
'persistent' => false,
'host' => 'localhost',
...
'log' => true, // Set this
]
]
如果您的應用程序處於調試模式,您現在將在頁面顯示 SQL 錯誤時看到 SQL 查詢。 如果您沒有打開調試模式,您還可以通過添加以下內容將 SQL 查詢記錄到文件中:
配置/app.php
找到Log
配置並添加新的日志類型:
'Log' => [
'debug' => [
'className' => 'Cake\Log\Engine\FileLog',
'path' => LOGS,
'file' => 'debug',
'levels' => ['notice', 'info', 'debug'],
'url' => env('LOG_DEBUG_URL', null),
],
'error' => [
'className' => 'Cake\Log\Engine\FileLog',
'path' => LOGS,
'file' => 'error',
'levels' => ['warning', 'error', 'critical', 'alert', 'emergency'],
'url' => env('LOG_ERROR_URL', null),
],
// Add the following...
'queries' => [
'className' => 'File',
'path' => LOGS,
'file' => 'queries.log',
'scopes' => ['queriesLog']
]
],
您的 SQL 查詢現在將寫入一個日志文件,您可以在/logs/queries.log
找到該/logs/queries.log
已添加 Database\\ConnectionManager::get()。 它取代了 getDataSource()
在 Cookbook 3.0 之后,您需要啟用Query Logging
並選擇文件或控制台日志記錄。
use Cake\Log\Log;
// Console logging
Log::config('queries', [
'className' => 'Console',
'stream' => 'php://stderr',
'scopes' => ['queriesLog']
]);
// File logging
Log::config('queries', [
'className' => 'File',
'path' => LOGS,
'file' => 'queries.log',
'scopes' => ['queriesLog']
]);
在Controller中,我們需要寫如下兩行
echo "<pre>";
print_r(debug($queryResult));die;
它將顯示所有結果以及 sql 查詢語法。 這里我們使用debug來顯示結果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.