[PHP] Laravel 5.5 打印SQL語句


[PHP] Laravel 5.5 打印SQL語句

四種方法

第一種方法:

打印SQL默認是關閉的,需要在/vendor/illuminate/database/Connection.php中打開。

//    protected $loggingQueries = false;
    protected $loggingQueries = true;

之后可在代碼中使用了:

public function index(){
        $result = DB::select('select * from activity');

        $log = DB::getQueryLog();
        var_dump($log);
    }

 

第二種方法:

如果不想開啟但需要臨時查看,可以這樣操作:

 public function index(){
        
        DB::connection()->enableQueryLog();
        
        $result = DB::select('select * from activity');

        $log = DB::getQueryLog();
        var_dump($log);
    }

 

第三種方法:

在需要打印的語句前,添加監聽

DB::listen(function($query) {
    $bindings = $query->bindings;
    $sql = $query->sql;
    foreach ($bindings as $replace){
        $value = is_numeric($replace) ? $replace : "'".$replace."'";
        $sql = preg_replace('/\?/', $value, $sql, 1);
    }
    dd($sql);
});

 

第四種方法:

在AppServiceProvider 中的boot方法中添加,代碼如 下文 紅色 代碼所示:

 

 
         
<?php

namespace App\Providers;

use Illuminate\Support\Facades\DB;


class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
$this->dumpSqlLog();

***
}

  public function dumpSqlLog(){
DB::listen(
function ($sql) {
foreach ($sql->bindings as $i => $binding) {
if ($binding instanceof \DateTime) {
$sql->bindings[$i] = $binding->format('\'Y-m-d H:i:s\'');
} else {
if (is_string($binding)) {
$sql->bindings[$i] = "'$binding'";
}
}
}

// Insert bindings into query
$query = str_replace(array('%', '?'), array('%%', '%s'), $sql->sql);

$query = vsprintf($query, $sql->bindings);

// Save the query to file
$logFile = fopen(
storage_path('logs' . DIRECTORY_SEPARATOR . date('Y-m-d') . '_query.log'),
'a+'
);
fwrite($logFile, date('Y-m-d H:i:s') . ': ' . $query . PHP_EOL);
fclose($logFile);
}
);
  }

} // Insert bindings into query $query = str_replace(array('%', '?'), array('%%', '%s'), $sql->sql); $query = vsprintf($query, $sql->bindings); // Save the query to file $logFile = fopen( storage_path('logs' . DIRECTORY_SEPARATOR . date('Y-m-d') . '_query.log'), 'a+' ); fwrite($logFile, date('Y-m-d H:i:s') . ': ' . $query . PHP_EOL); fclose($logFile); } ); } /** * Register any application services. * * @return void */ public function register() { // }}
 

日志在  storage/log/xxx_query.log

 

本博客地址: wukong1688

本文原文地址:https://www.cnblogs.com/wukong1688/p/10933635.html

轉載請著名出處!謝謝~~

 

今日心得:

如果你不放棄自己,那么,沒有人能讓你放棄!

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM