How to get SQL Query on model->save() in CakePHP 3?

不问归期 提交于 2019-12-23 10:43:08

问题


How can I view the SQL Query on model->save() in CakePHP 3? Is there any way to do this? I want to get the specific sql query e.g when I save new entity.

I need it because I want to save that to a log file in some cases.

My bootstrap.php log config:

Log::config('current', [
    'className' => 'File',
    'path' => LOGS.DS.date('Y-m').DS,
    'scopes' => ['daily','queriesLog'],
    'file' => date('Y-m-d'),
]);

What i want to get:

e.g when i save entity:

$this->Clients->save($client);

i want to log something and i want to save INSERT sql query with this log

Log::warning('test\n', ['scope' => ['daily']]);

回答1:


A solution could be using query logging

http://book.cakephp.org/3.0/en/orm/database-basics.html#query-logging

you can turn query logging on just when you save your model and then turn it off

For example I have a Comments model

In my bootstrap.php I did

Log::config('current', 
[ 
    'className' => 'File', 
    'path' => LOGS.date('Y-m').DS, // you don't need a DS between LOGS and date()
    'scopes' => ['daily','queriesLog'], 
    'file' => date('Y-m-d'), 
]);

and in my controller I did

$conn = \Cake\Datasource\ConnectionManager::get('default');
$comment = $this->Comments->get(5620); // 5620 is the id of one comments of mine
$conn->logQueries(true);
$comment = $this->Comments->get(5619); // 5619 is onother id of one comments of mine
$comment->text = 'Test';
$this->Comments->save($comment);
$conn->logQueries(false);

In this way a file is created in the logs folder and the file contains the following

2015-12-16 13:38:35 Debug: SELECT ... WHERE Comments.id = 5619 LIMIT 1
2015-12-16 13:38:35 Debug: BEGIN
2015-12-16 13:38:35 Debug: UPDATE comments SET text = 'Test' WHERE id = 5619
2015-12-16 13:38:35 Debug: COMMIT

note that the query used to get comment #5620 has not been logged

Also note that this works if you don't have debugkit enabled




回答2:


Put this into model

 function getLastQuery() {
        Configure::write(‘debug’,false);
        $dbo = $this->getDatasource();
        $logs = $dbo->getLog();
        $lastLog = end($logs['log']);
        $latQuery = $lastLog['query'];
        echo "<pre>";
        print_r($latQuery);
    }
after $this->save($data);

call that function

$this->getLastQuery();

and echo it.

Try it.



来源:https://stackoverflow.com/questions/34292400/how-to-get-sql-query-on-model-save-in-cakephp-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!