Laravel显示帖子上的最后回复 [英] Laravel show last reply left on post

查看:38
本文介绍了Laravel显示帖子上的最后回复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试显示帖子上留下的最后一个回复.但是只有名称和日期.我尝试了以下事情

I'm trying to show the last reply that was left on a post. But only the name and date of it. I tried the following things

我认为这个人应该做的是查看帖子的回复.按ID对它们进行排序,然后显示第一个用户名.但这是行不通的. $ topic->回复-> sortBydesc('id')-> first()->用户->用户名}}

What I think this one should do is look at the replies to the post. Sort them by ID and then display the first one's username. But it doesn't work. $topic->replies->sortBydesc('id')->first()->user->username }}

我也尝试了这个,我在整个论坛中要求所有答复,并显示最后一个.它有效,但我不是与该职位相关的人. {{$ allposts-> sortBydesc('id')-> first()->用户->用户名}}

I also tried this one where I requested all the replies in the entire forum and displayed the last one. It worked but I wasn't the one related to the post. {{ $allposts->sortBydesc('id')->first()->user->username }}

有人知道我该怎么做吗?目前,我正在将这两个参数传递给视图(这些没有问题,它们可以工作,但我认为应该添加一些内容)

Does anyone know how I can make this work? Currently, i'm passing these two into the view (There is nothing wrong with these, they work but I think there should be something added)

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 reply ,则需要急于加载.另外,如果您与 user 有关系,谁也急于加载它.

If you are trying to get topic's replies you need to eager load. Also if you have relation with user who replied eager load it as well.

使用 latest()方法获取最新回复.

Use latest() method for getting latest replies.

仅对于名称 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'));
}

这篇关于Laravel显示帖子上的最后回复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆