如何在 CakePHP 3.2 中获取最后一个 运行 查询?

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?

Database\ConnectionManager::get() has been added. It replaces 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']
]);

Cookbook 3.0 - Query Logging

简而言之:您需要做的就是修改 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 查询记录到文件中:

config/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

中找到该文件

在Controller中,我们需要写两行如下

echo "<pre>";
print_r(debug($queryResult));die; 

它将显示所有结果以及 sql 查询语法。 这里我们使用 debug 作为显示结果。