Help us understand the problem. What is going on with this article?

【Laravel】withメソッドを使用して多対多で発行されるクエリ数を削減する方法

多対多

例えば以下のような例。
トピック:topics
タグ:tags
中間テーブル:topic_tag

やりたいこと

各トピックごとに紐付いているタグ全件を取得する。

変更前

<?php

namespace App\Model;

use Illuminate\Database\Eloquent\Model;
use App\Model\Tag;

class Topic extends Model
{
    protected $table = 'topics';
    protected $guarded = ['id', 'user_id'];

    public static function fetchWithTags($order='desc'){
        $query = self::where('user_id', Auth::id())->orderBy('created_at', $order);
        return $query->get();
    }

    public function tags()
    {
        return $this->belongsToMany(Tag::class, 'topic_tag');
    }
}

[2019-12-07 21:56:30] local.DEBUG: 17.52 ms -> select * from `users` where `id` = ? 
bind: array (
  0 => 1,
)  
[2019-12-07 21:56:30] local.DEBUG: 0.8 ms -> select * from `topics` where `user_id` = ? order by `conversed_at` desc
bind: array (
  0 => 1,
)  
[2019-12-07 21:56:30] local.DEBUG: 0.82 ms -> select `tags`.*, `tag_topic`.`topic_id` as `pivot_topic_id`, `tag_topic`.`tag_id` as `pivot_tag_id` from `tags` inner join `tag_topic` on `tags`.`id` = `tag_topic`.`tag_id` where `tag_topic`.`topic_id` = ?
bind: array (
  0 => 4,
)  
[2019-12-07 21:56:30] local.DEBUG: 0.78 ms -> select `tags`.*, `tag_topic`.`topic_id` as `pivot_topic_id`, `tag_topic`.`tag_id` as `pivot_tag_id` from `tags` inner join `tag_topic` on `tags`.`id` = `tag_topic`.`tag_id` where `tag_topic`.`topic_id` = ?
bind: array (
  0 => 3,
)  
[2019-12-07 21:56:30] local.DEBUG: 0.86 ms -> select `tags`.*, `tag_topic`.`topic_id` as `pivot_topic_id`, `tag_topic`.`tag_id` as `pivot_tag_id` from `tags` inner join `tag_topic` on `tags`.`id` = `tag_topic`.`tag_id` where `tag_topic`.`topic_id` = ?
bind: array (
  0 => 2,
)  
[2019-12-07 21:56:30] local.DEBUG: 0.87 ms -> select `tags`.*, `tag_topic`.`topic_id` as `pivot_topic_id`, `tag_topic`.`tag_id` as `pivot_tag_id` from `tags` inner join `tag_topic` on `tags`.`id` = `tag_topic`.`tag_id` where `tag_topic`.`topic_id` = ?
bind: array (
  0 => 1,
)  

変更後

<?php

namespace App\Model;

use Illuminate\Database\Eloquent\Model;
use App\Model\Tag;

class Topic extends Model
{
    protected $table = 'topics';
    protected $guarded = ['id', 'user_id'];

    public static function fetchWithTags($order='desc'){
        $query = self::where('user_id', Auth::id())->orderBy('created_at', $order);

        // withを使ってみる
        $query->with([
                'tags' => function ($tags_query) {
                    $tags_query->orderBy('created_at', 'desc');
                },
            ]
        );

        return $query->get();
    }

    public function tags()
    {
        return $this->belongsToMany(Tag::class, 'topic_tag');
    }
}
[2019-12-07 21:55:20] local.DEBUG: 20.12 ms -> select * from `users` where `id` = ? 
bind: array (
  0 => 1,
)  
[2019-12-07 21:55:20] local.DEBUG: 0.73 ms -> select * from `topics` where `user_id` = ? order by `conversed_at` desc
bind: array (
  0 => 1,
)  
[2019-12-07 21:55:20] local.DEBUG: 0.92 ms -> select `tags`.*, `tag_topic`.`topic_id` as `pivot_topic_id`, `tag_topic`.`tag_id` as `pivot_tag_id` from `tags` inner join `tag_topic` on `tags`.`id` = `tag_topic`.`tag_id` where `tag_topic`.`topic_id` in (1, 2, 3, 4) 

表示用のblade

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
        @foreach($topics as $topic)
            <div class="card">
                <div class="card-header">
                    <span>{{ $topic->title }}</span>
                </div>
                <div class="card-body">
                @foreach($topic->tags as $tag)
                    <div>{{ $tag->name }}</div>
                @endforeach
                </div>
            </div>
        @endforeach
        </div>
    </div>
</div>
@endsection

分かったこと

各トピックに対してタグを検索するSQLが発行されていたのが、withを使用することによりタグを取得するSQLが1回だけに削減された。

この方法はEagerロードと呼ばれている。
https://readouble.com/laravel/6.x/ja/eloquent-relationships.html

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away