Laravel Eloquent:获取模型查询生成的 SQL 语句
我们有时候想测试一段代码生产的 SQL 语句,比如: 我们想看 App\User::all();
产生的 SQL 语句,我们简单地使用路由闭包做个实验:
Route::get('/test-sql', function() {
DB::enableQueryLog();
$user = App\User::all();
return response()->json(DB::getQueryLog());
});
然后我们在浏览器打开 http://www.example.com/test-sql
即可看到 $user = User::all();
所产生的 SQL 了。
[
{
query: "select * from `users` where `users`.`deleted_at` is null",
bindings: [ ],
time: 1.37
}
]
如果需要经常查看 SQL 信息,推荐使用 clockwork 这个插件更友好的记录。
补充下,如果想查看所有的 query,还可以使用 监听查询事件:
API 开发用这个包也很方便
https://github.com/overtrue/laravel-query-...
@leoyang QueryExecuted这个类哪个版本开始有的
还有能输出当前链接使用的ip和端口吗
https://learnku.com/courses/laravel-packag...
这个比较好使用
使用helper str_replace_array()可以把SQL和binding结合成完整的SQL语句
可以在中间件实现