Laravel Eloquent display query log

2022-08-30 08:59:38
use App\Order;
 
public function show(Order $order) {
    $data = $order->all();
    return dd($order->getQueryLog());

有没有办法显示Eloquent在Laravel中构建的查询?

我试过了,但它不起作用getQueryLog();


答案 1

首先,您必须启用查询日志,它可以使用

DB::connection()->enableQueryLog();

然后您可以使用下面的代码来查看查询日志

$queries = DB::getQueryLog();

如果要查看上次执行的查询

$last_query = end($queries);

要了解有关日志记录的更多信息,请参阅此 https://laravel.com/docs/5.0/database#query-logging

public function show(Order $order){
    \DB::connection()->enableQueryLog();
    $data = $order->all();
    $queries = \DB::getQueryLog();
    return dd($queries);
}

答案 2

要查看文件中的查询日志,您可以按以下步骤操作。laravel.log

namespace App\Providers;

use DB;
use Log;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        DB::listen(function($query) {
            Log::info(
                $query->sql,
                $query->bindings,
                $query->time
            );
        });
    }

    // ...
}

推荐