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

9

我想在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中实现此功能?


2
在CakePHP 3.x中可能需要更多的工作,您可能需要使用自定义查询记录器类。我可以问一下您的实际用例,即为什么您需要访问最后一个查询? - ndm
1
我在将数据保存到数据库时遇到了一些问题,因此我需要帮助。 - sradha
3个回答

14
简单来说,你只需要修改 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中找到它。


0
新增了Database\ConnectionManager::get(),它替代了getDataSource()。
根据Cookbook 3.0的指南,您需要启用“查询日志记录”,并选择文件或控制台日志记录。
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 - 查询日志记录


我无法使用它。请告诉我在哪里可以保存这些代码? - sradha
@sradha等人:配置“Log”应在应用程序的引导阶段完成。请注意,查询记录在“debug”日志级别下,该级别在app.default.php中默认设置为写入LOGS目录中的文件(在 'Log' => ['debug' => [...] ]),因此,如果您将至少该部分复制到自己的app.php中,则您只需要在数据库配置中将log设置为true,或者调用logQueries(例如,ConnectionManager::get('default')->logQueries(true))。 - Synexis

0
在控制器中,我们需要编写以下两行代码。
echo "<pre>";
print_r(debug($queryResult));die; 

它将显示所有结果以及SQL查询语法。 在这里,我们使用debug来显示结果。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接