11
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Laravel 8のexplainをLaravel7以下で使う

Last updated at Posted at 2020-12-10

何がしたいか

Laravel8 でexplainメソッドが追加されました。

User::where('id',1)->explain()->dump();
DB::table('id',1)->where('id',1)->explain()->dump();

Laravel8未満でも使いたいなーと思いやってみることに

環境

下記環境で動作を確認してます。
Laravel 7.x

やり方

macroで拡張できるので、メソッドを追加して、マージされたプルリクの内容をAppServiceProviderにペタリ

AppServiceProvider
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
use Illuminate\Database\Query\Builder as QueryBuilder;


    public function boot(): void
    {
        QueryBuilder::macro('explain', function () {
            $sql = $this->toSql();

            $bindings = $this->getBindings();

            $explanation = $this->getConnection()->select('EXPLAIN ' . $sql, $bindings);

            return collect($explanation);
        });
        EloquentBuilder::macro('explain', function () {
            $sql = $this->toSql();

            $bindings = $this->getBindings();

            $explanation = $this->getConnection()->select('EXPLAIN ' . $sql, $bindings);

            return collect($explanation);
        });
    }

これでとれるようになった。

User::where('id',1)->explain()->dump();
DB::table('id',1)->where('id',1)->explain()->dump();

ログに出す

そもそも、ログ出すのに使う必要ないので、explainメソッドいらない子かもしれない...
サービスプロバイダのbootに下記を追加(参考)

AppServiceProvider
DB::listen(function ($query) {
    if (!preg_match("/^EXPLAIN/", $query->sql)) {
        $explain = DB::select("EXPLAIN  {$query->sql}", $query->bindings);
        Log::info($explain);
    }
});
11
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?