[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
转载请著名出处!谢谢~~
今日心得:
如果你不放弃自己,那么,没有人能让你放弃!