How to eager load the 'user' function from

2019-09-02 16:23发布

问题:

NOTE: The relationship between Post and Tag model is many to many and the relationship between User and Post model is one to Many. Everything is working well I just have too many Queries from users where users.id... when debbug it. I want to use eager loading for the user function, in this situation in my controller function. How do I use it like with('user')->get();

Thanks.

This is my web.php route:

Route::get('/posts/tags/tag/{tag}', 'TagsController@show');

This is my controller function for that:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Tag; use App\Post;

class TagsController extends Controller {

public function __construct()

{

    $this->middleware('auth')->except(['index']);

}



public function index(Tag $tag)

{


    return view('posts.index', compact('tag'));
}

public function create()

{
    return view('tags.create');
}

public function store(Request $request)

{

    $this->validate(request(), [

        'name' => 'required|max:255'

    ]);

    Tag::create([

        'name' => request('name')            

    ]);


    return redirect('/');
}

public function show(Tag $tag)
{


    return view('tags.show', compact('tag'));
}

}

This is my show.blade.php:

@foreach ($tag->posts as $post)

              <div class="col-sm-6" >

                  <div class="card" style="margin-bottom:15px;">
                    <img class="card-img-top" src="https://neilpatel-qvjnwj7eutn3.netdna-ssl.com/wp-content/uploads/2015/07/seoimage.jpg" height="270px" alt="Card image cap">
                    <div class="card-body">
                      <h5 class="card-title">
                          <a href="/posts/{{ $post->id }}">
                          {{ $post->title }}
                        </a>
                      </h5>
                      <p class="card-text">
                       {{ substr(strip_tags($post->body), 0, 50) }}{{ strlen(strip_tags($post->body)) > 50 ? "..." : "" }}
                      </p>
                      <p class="card-text"><small class="text-muted">{{ $post->user->name }} on
                                {{ $post->created_at->toFormattedDateString() }}</small></p>
                      <hr>
                      <a href="/posts/{{ $post->id }}" class="btn btn-warning">Go somewhere</a>
                    </div>
                  </div>
                </div>
@endforeach

This is my queries (images below):

QUERIES IMAGE 1

QUERIES IMAGE 2

回答1:

In your controller, you can do it like this below and the blade code stays the same.

$posts = Post::with('user')->get();

or

$posts = Post::with(['user'])->get();

Hope this works for you.



回答2:

You can use a combination of eager loading and lazy eager loading in your controller's show() method. Try something like this:

public function show(Tag $tag)
{
    $tag->load(['posts' => function($query) {   // lazy eager load posts
        $query->with('user');                   // eager load users
    }]);

    return view('tags.show', compact('tag'));
}

https://laravel.com/docs/5.7/eloquent-relationships#lazy-eager-loading