我试图显示帖子中留下的最后一个回复。但只有它的名称和日期。我尝试了以下事情
我认为这个应该做的是查看对帖子的回复。 按 ID 对它们进行排序,然后显示第一个的用户名。但它不起作用。$topic->replies->sortBydesc('id')->first()->user->username }}
我也尝试了这个,我请求了整个论坛中的所有回复并显示了最后一个。它有效,但我不是与帖子相关的那个。{{ $allposts->sortBydesc('id')->first()->user->username }}
有谁知道我如何做到这一点? 目前,我正在将这两个传递到视图中(这些没有问题,它们有效,但我认为应该添加一些内容(
public function show($id)
{
$topics = Topic::with('theme')->find($id);
$theme = Theme::with('topics')->find($id);
return view('themes.theme')->with('topics', $topics)->with('theme', $theme);
}
提前致谢
如果你想得到topic
的replies
你需要急于加载。此外,如果您与回复急切加载的user
有关系。
使用latest()
方法获取最新回复。
只有name
和date
我们有select()
.
public function show($id)
{
$topics = $topic->with('replies' => function($query) {
$query->with('user')->select('name', 'created_at')->latest();
});
$theme = Theme::with('topics')->find($id);
return view('themes.theme', compact('topics', 'theme'));
}