samedi 30 décembre 2017

Getting a Thread with its latest Post within the same object, latest() creates a huge overhead

Suppose I have this in my model called Thread.php:

public function post()
{
    return $this->hasMany('App\Post');
}

public function latestPost()
{
    return $this->hasOne('App\Post')->latest('id');
}

I have a page which displays all threads with their latest post. To do so, I do something like

all_threads = Thread::with('latestPost')->get();

It does this query:

select * from `posts` where `posts`.`thread_id` in ('1', '2', '3', '4', '5', '6', '7', '8', '9', '10') order by `id` desc

It works, but latestPost() is grabbing all posts in the table, for each thread, and then returning the latest one. This is making thousands of unnecessary objects and the overhead is already high.

The ideal would be to just take the latest Post record, but I'm not sure how to do it with Eloquent.

I've tried the following:

return $this->hasOne('App\Post')->orderBy('id', 'desc')->limit(1);
// or
return $this->hasOne('App\Post')->latest('id')->take(1);

But then only the last Thread object comes with a latestPost record. How can I optimize this query while still using Eloquent?

Thanks



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire