如何在CakePHP 3.2中获取上次运行的查询? [英] How to get last run query in CakePHP 3.2?

查看:81
本文介绍了如何在CakePHP 3.2中获取上次运行的查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在CakePHP 3.2中获得最后执行的查询,我之前在CakePHP 2.x中使用了以下内容:-

I want to get the last executed query in CakePHP 3.2, I have used the following in CakePHP 2.x before:-

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

How can i do it in CakePHP 3.x?

推荐答案

简而言之:您只需要修改 config/app.php

In plain English: All you need to do is modify 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查询记录到文件中:

If your app is in debug mode, you will now see the SQL query when your page displays a SQL error. If you do not have debug mode on, you can log the SQL queries to a file by also adding the following:

config/app.php

找到Log配置并添加新的日志类型:

Find the Log configuration and add a new log type:

'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

Your SQL queries will now be written to a log file which you can find in /logs/queries.log

这篇关于如何在CakePHP 3.2中获取上次运行的查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆