您的位置:首页 > 编程语言 > PHP开发

laravel打印sql语句

2016-11-22 15:32 183 查看
打印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
等等,很是好用,

GitHub地址:https://github.com/itsgoingd/clockwork

中文地址: http://laravelacademy.org/post/3746.html

安装完以后,直接在
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/

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: