本文介绍了laravel5.* 打印出执行的sql语句的方法,分享给大家,具体如下:
打开appprovidersappserviceprovider.php,在boot方法中添加如下内容
5.2以下版本
// 先引入db
use db;
// 或者直接使用 db::
db::listen(function($sql, $bindings, $time) {
dump($sql);
});
5.2及以上版本
use db;
// 或者直接使用 db::
// 只能接受一个参数
queryexecuted {#84 ▼
+sql: "select * from `posts` where `slug` = ? limit 1"
+bindings: array:1 [▶]
+time: 0.59
+connection: mysqlconnection {#85 ▶}
+connectionname: "mysql"
}
db::listen(function($sql) {
dump($sql);
// echo $sql->sql;
// dump($sql->bindings);
});
// 如果要放入日志文件中
db::listen(
function ($sql) {
// $sql is an object with the properties:
// sql: the query
// bindings: the sql query variables
// time: the execution time for the query
// connectionname: the name of the connection
// to save the executed queries to file:
// process the sql and the bindings:
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);
}
);
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持硕编程。
【说明】:本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!