Laravel 4性能调试–调试SQL查询

Laravel 3有个非常好的调试工具。它就是Daylee Rees开发的Anbu。最终被Laravel的创建者Taylor加入到核心中。而Laravel 4, 到现在为止,还未发现这种类型的调试工具。那我们该如调试数据库的SQL查询呢?


下面是几种解决方案:

1、使用Loic Sharma’s Profiler。这是一个PHP5.3的调试器,它基于Laravel3的Anbu。我暂时还未测试,所以请按照文档进行使用吧。

2、使用Profiler by Juy。它基于PHP 5.3,支持Laravel 4。后端基于,sorora/omni,前端基于loic-sharma/profiler,部分特性借鉴papajoker/profiler。

3. Create an event that will listen to illuminate.query. Open your routes.php file and add this at the bottom:

Event::listen('illuminate.query',function($sql)
{
    var_dump($sql);
});

This will print every query on the screen on the place where it is called so it might not look pretty,especially in loops. Also you might not see the queries on the screen in some cases since they will be “hidden” in the HTML source code (so just view the page source to see them, they will usually be at the top of the page)

4. You can also display the last executed query by placing a code in front of the code that executes a query. For example let say we have this code in our controller:

// Grab all the users
$customers= Customer::orderBy('name','asc')->get();

Place the Event::listen code in front of that statement and you will see that query displayed on your screen.

// dump the next executed query and die (dd)
Event::listen('illuminate.query',function($sql)
{
    dd($sql);
});
 
// Grab all the users
$customers= Customer::orderBy('name','asc')->get();

Keep in mind that this will only display 1 query. If your statement calls more queries they will not get displayed.

5. Put the following code in the App::before filter to get a dump of your database queries:

DB::listen(function($sql,$bindings,$time)
{
    var_dump($sql);
    var_dump($bindings);
});

6. There is another “trick” that I use sometimes (because having SQL queries displayed all the time is not practical and it messes up the code and design): I intentionally make an error in my SQL statement. For example here I mistyped type as tyspe:

$contracts= Contract::where('tyspe','=',0)->orderBy('note','asc')->get();

Since tyspe doesn’t exist Laravel returns an error,showing me the complete SQL statement:

SQLSTATE[42S22]: Column not found: 1054 Unknown column ‘tyspe’ in ‘where clause’ (SQL: select * from `contracts` where `tyspe` = ? order by `note` asc) (Bindings: array ( 0 => 0, ))

Let me know if you know of any other solutions in the comments.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值