8

我想在 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 中做到这一点?

4

3 回答 3

13

简而言之:你需要做的就是修改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

于 2016-11-26T21:43:43.797 回答
0

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']
]);

Cookbook 3.0 - 查询日志

于 2016-02-09T13:09:33.457 回答
0

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

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

它将显示所有结果以及 sql 查询语法。这里我们使用调试来显示结果。

于 2020-07-23T05:05:35.360 回答