本文主要是介绍laravel打出sql语句,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
方法一
orm直接调用toSql()方法,如:
$sql = UserModel::query()->where('role','2')->toSql();
dd($sql); //select * from User_table where role = '2'
方法二
打开app\Providers\AppServiceProvider.php,在boot方法中添加如下内容
5.2以下版本
use DB;
DB::listen(function($sql, $bindings, $time) {dump($sql);});
5.2及以上版本
use DB;
QueryExecuted {+sql: "select * from `posts` where `slug` = ? limit 1"+bindings: array:1 [▶]+time: 0.59+connection: MySqlConnection {+connectionName: "mysql"
}DB::listen(function($sql) {dump($sql);});
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'";}}}$query = str_replace(array('%', '?'), array('%%', '%s'), $sql->sql);$query = vsprintf($query, $sql->bindings);$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);}
);
这篇关于laravel打出sql语句的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!