laravel打印sql语句

打印sql语句,直接在你执行SQL语句后输出

方法一:

$queries = DB::getQueryLog();

 $a = end($queries);

 $tmp = str_replace('?', '"'.'%s'.'"', $a["query"]);

 echo vsprintf($tmp, $a['bindings']);

 exit;

方法二:  可以把下面代码放在查询语句前:

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

 方法三:

下载 clockwork 扩展,这个扩展可以在很多框架里调试,比如laravel,lumen,CI等等,很是好用,

安装完以后,直接在firebug里可以看到执行的语句!

方法四:

自己写

执行

php artisan make:listener QueryListener

会生成app/Listeners/QueryListener.php文件

然后把handler修改成下面这样

namespace App\Listeners;

use Illuminate\Database\Events\QueryExecuted;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;

class QueryListener
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    public function handle(QueryExecuted $event)
    {
        $sql = str_replace("?", "'%s'", $event->sql);

        $log = vsprintf($sql, $event->bindings);

        \Log::info($log);
    }

}

打开 app/Providers/EventServiceProvider.php ,在 $listen 中添加

    protected $listen = [
        'App\Events\SomeEvent' => [
            'App\Listeners\EventListener',
        ],
        'Illuminate\Database\Events\QueryExecuted' => [
            'App\Listeners\QueryListener'
        ]
    ];

然后在 自己的storage\log\ 下看自己的日志吧!

类似这样

[2017-01-02 02:50:09] local.INFO: select count(*) as aggregate from `g9zz_posts`  
[2017-01-02 02:50:09] local.INFO: select * from `g9zz_posts` limit 30 offset 0  
[2017-01-02 02:50:09] local.INFO: select * from `g9zz_categories` where `g9zz_categories`.`id` in ('1', '6', '5', '3', '4')  
[2017-01-02 02:50:09] local.INFO: select * from `g9zz_users` where `g9zz_users`.`id` in ('8', '12', '10', '16', '5')  
[2017-01-02 02:50:09] local.INFO: select * from `g9zz_users` where `g9zz_users`.`id` in ('11', '17', '0')  

建议把日志换成daily的,不然日志大小会爆炸的哦(config/app.php 里的APP_LOG)

转载自: http://www.iphpt.com/detail/75/

 

 

posted @ 2016-11-22 15:32  isykw  阅读(18238)  评论(0编辑  收藏  举报