Laravel 有很多最新的模型

问题描述 投票:0回答:1

我正在使用 laravel 10。

我在数据库中有以下结构

forum_categories
  id

forum_threads
  id
  forum_category_id

forum_posts
  id
  forum_thread_id

我的目标是,使用最新的 ForumPost 模型雄辩地获取所有类别。

在模型 ForumCategory 中我有以下方法:

public function posts(): HasManyThrough
    {
        return $this->hasManyThrough( ForumPost::class, ForumThread::class);
    }

我的疑问:

$categories =  ForumCategory::with(['posts' => function ($q) {
            $q->with('author')->latest();
        }])->get();

它工作正常,但它加载所有论坛帖子,而不仅仅是最后一个。

那么,如何只检索每个类别的最后一篇 ForumPost 呢?

谢谢你。

laravel eloquent
1个回答
0
投票

您可以在

hasOneThrough
中定义另一个关系
ForumCategory
来获取最新的帖子,例如,

public function latestPost()
{
    return $this->hasOneThrough(ForumPost::class, ForumThread::class)->latest('id');
}

然后,

$categories = ForumCategory::with('latestPost.author')->get();
© www.soinside.com 2019 - 2024. All rights reserved.