M
M
Maxim2021-02-15 12:08:08
Laravel
Maxim, 2021-02-15 12:08:08

Is it possible to optimize queries?

Is it possible to somehow optimize requests for the output of a post, comments to it and tags

there is a Post model

class Post extends Model
{
    use HasFactory;

    protected $table = 'posts';


    public function comments()
    {
        return $this->hasMany(Comment::class);
    }

    public function tags()
    {
        return $this->hasMany(Tag::class);
    }
}


output like this in the controller

public function single(int $id){
        $post = Post::find($id);

        $comments = $post->comments()->latest()->take(20)->get();
        $tags = $post->tags()->latest()->take(5)->get();

        return view('single', compact(['post','comments','tags']));
    }


in the debugger it issues 3 requests, can this be somehow optimized to one? Or through connections in another way?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
J
JhaoDa, 2021-02-15
@JhaoDa

Or through connections in another way?
Yes.

I
Ivan, 2021-02-15
@vhuk1802

try adding ->with('comments')

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question