各种打印sql方法

1. getQueryLog(获取的是最近的sql即开启enableQueryLog时刻算起)

 DB::connection()->enableQueryLog();
       //要执行的查询语句
 dump(DB::getQueryLog());

2. 封装方法(新建一个helper.php文件,利用composer自动加载)

if(! function_exists('query_log')){

        function query_log($callback)
    	{
	        /**
	         * Print the current sql and Output 
	         *
	         * @param  Closure  $callback
	         * @return array
	         */
	        DB::connection()->enableQueryLog();
	        if( $callback instanceof \Closure){
	            $callback();
	        }
        	dump(DB::getQueryLog());
    	}
}

3. 接收应用程序执行的每个 SQL 查询,可以使用 listen 方法。 此方法对于记录查询或调试很有用,服务提供者中注册你的查询侦听器:

<?php

namespace App\Providers;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * 引导应用程序服务
     *
     * @return void
     */
    public function boot()
    {
        DB::listen(function ($query) {
            // $query->sql
            // $query->bindings
            // $query->time
        });
    }

    /**
     * 注册服务提供者
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

4. toSql方法

$query = \DB::table('users')->where('name', 'myname');

echo $query->toSql();

想要绑定数据?使用以下方法:

$query = \DB::table('users')->where('name', 'myname'); 
$sql = str_replace_array('?', $query->getBindings(), $query->toSql()); 

echo $sql;

5. 自定义一个 macroable'带有获取绑定数据的 SQL 查询替换 toSql

宏定义是为类动态的增加方法

添加以下宏方法到 AppServiceProvider boot()方法下
\Illuminate\Database\Query\Builder::macro('toRawSql', function(){
    return array_reduce($this->getBindings(), function($sql, $binding){
        return preg_replace('/\?/', is_numeric($binding) ? $binding : "'".$binding."'" , $sql, 1);
    }, $this->toSql());
});
\Illuminate\Database\Eloquent\Builder::macro('toRawSql', function(){
    return ($this->getQuery()->toRawSql());
});
调试
echo \DB::table('users')->where('name', 'myname')->toRawSql();
echo User::where('name', 'myname')->toRawSql();

更多推荐

打印sql各种方法汇总