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']]);
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With