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

How can I view the SQL query in model-> save () in CakePHP 3? Is there any way to do this? I want to get a specific sql request, for example, when I save a new object.

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

My bootstrap.php log configuration:

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

What I want to get:

For example, when I save an object:

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

I want to write something, and I want to save the SQL INSERT query with this log

 Log::warning('test\n', ['scope' => ['daily']]); 
+5
source share
2 answers

The solution may use query logging

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

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

For example, I have a comment 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('Ym-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); 

Thus, the 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 request used to get comment # 5620 was not logged

Also note that this works if you are not using debugkit

+2
source

Put it in the 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 this function

 $this->getLastQuery(); 

and repeat it.

Give it a try.

-1
source

Source: https://habr.com/ru/post/1238284/


All Articles