I’m using laravel 10.
I have following structure in DB
forum_categories
id
forum_threads
id
forum_category_id
forum_posts
id
forum_thread_id
My goal is, using the eloquent get all categories with latest ForumPost model.
In model ForumCategory i have following method:
public function posts(): HasManyThrough
{
return $this->hasManyThrough( ForumPost::class, ForumThread::class);
}
And my query:
$categories = ForumCategory::with(['posts' => function ($q) {
$q->with('author')->latest();
}])->get();
It works fine but it loads all ForumPosts not only the last one.
So, how to retrieve only the last one ForumPost for each category?
Thank you.
2
Answers
you can define another relationship
hasOneThrough
in yourForumCategory
to fetch the latest post like,and then,
To retrieve only the latest ForumPost for each category, you can modify your query to use a subquery to select the latest post for each category. Here’s how you can do it in Laravel:
Make sure you have proper indexes set up on your database tables to optimize the performance of this query, especially if you have a large dataset.