方案一:toSql()
$sql_orders = Order::where('user_id', $user_id);
Log::debug($sql_orders->toSql());
日志输出为:
local.DEBUG: select * from orders
where user_id
= ?
方案二:DB::getQueryLog()
显示最后一条查询
DB::enableQueryLog(); // 注意,在查询前,需要启用查询日志
$sql_orders = Order::where('user_id', $user_id);
$sql_orders->get();
Log::debug(DB::getQueryLog());
日志输出为
local.DEBUG: array (
0 =>array (
'query' => 'select * from `orders` where `user_id` = ?,
'bindings' =>
array (
0 => 3,
),
'time' => 0.92,
),
)
参考: https://stackoverflow.com/questions/18236294/how-do-i-get-the-query-builder-to-output-its-raw-sql-query-as-a-string
方案三:监听查询事件
参考:https://artisansweb.net/how-to-log-query-in-laravel/
app/Providers/AppServiceProvider.php boot 方法中添加监听。
方案四:Laravel Debugbar
https://github.com/barryvdh/laravel-debugbar
看上去是最简单直观的方式。