数据库查询语句

2025-01-14 05:56:47
推荐回答(1个)
回答1:

在使用 Laravel 的时候,很多时候我们想知道背后执行的数据库查询语句是什么。
这个其实可以有一个很简单的方法:

在 app\Providers\AppServiceProvider 里面:

public function boot()    {        if ( $this->app->environment() === 'local' ) {           \Log::info(\DB::getQueryLog());        }    }

如果没有效果的话,记得在代码前面执行 DB::enableQueryLog()。在使用 tinker 的情况下也是可以的:

⚡ php artisan tinkerPsy Shell v0.7.0 (PHP 7.0.4-7+deb.sury.org~wily+2 — cli) by Justin Hileman>>> DB::enableQueryLog(); => null>>> App\User::all();=> Illuminate\Database\Eloquent\Collection {#771     all: [       App\User {#777         ...       },       App\User {#778         ...       },       ...     ],   }>>> DB::getQueryLog();=> [     [       "query" => "select * from "users"",       "bindings" => [],       "time" => 0.32,     ],   ]

主要在 tinker 最开始的时候执行 DB::enableQueryLog() ,然后你执行完数据库查询后,就可以使用 DB::getQueryLog() 查看了