Laravel 打印SQL语句

本文展示了在Laravel中如何开启查询日志,并通过`DB::getQueryLog()`打印SQL语句及其执行时间。示例中涉及了Eloquent ORM的查询构造器用法,包括`with()`方法来加载关联数据,以及`offset()`、`limit()`和`orderBy()`进行分页和排序。通过对查询日志的分析,可以优化数据库查询效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

类class之前记得引用use Illuminate\Support\Facades\DB;

在方法里面这样干

DB::connection()->enableQueryLog();#开启执行日志

$product = $product->where('product_first_category_id', '=', $val['id'])->where('product_status', '=', 20);

            $result = $product->with([
                'images' => function ($query) {
                    $query->where('is_delete', '=', 10)->where('is_default', '=', 1);
                },
                'product_spec' => function ($query) {
                    
                }
            ])->offset(0)->limit($limit)->orderBy('id', 'desc')->get()->toArray();

print_r(DB::getQueryLog());//打印SQL语句

结果如下:

Array ( [0] => Array ( [query] => select * from `product` where `is_delete` = ? and `product_first_category_id` = ? and `product_status` = ? order by `id` desc limit 6 offset 0 [bindings] => Array ( [0] => 10 [1] => 1 [2] => 20 ) [time] => 0.62 ) [1] => Array ( [query] => select * from `product_images` where `product_images`.`product_id` in (?, ?, ?) and `is_delete` = ? and `is_default` = ? [bindings] => Array ( [0] => 8 [1] => 10 [2] => 12 [3] => 10 [4] => 1 ) [time] => 0.47 ) [2] => Array ( [query] => select * from `product_spec` where `product_spec`.`product_id` in (?, ?, ?) [bindings] => Array ( [0] => 8 [1] => 10 [2] => 12 ) [time] => 0.44 ) )

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值