首页 > 解决方案 > Laravel 获取最后一篇文章的主题

问题描述

我正在尝试这样做,按谁有新帖子获取主题列表,所以我在主题模型中创建一个这样的关系

public function latest_post()
{
    return $this->hasOne(Post::class)->latest();
}

然后我使用了这样的查询

Topic::where('locale',$this->locale)->with('latest_post')->paginate(15)->sortByDesc('latest_post.created_at');

但它给了我一个错误

Collection::render 不存在

所以我把它sort改成orderBy那样

Topic::where('locale',$this->locale)->with('latest_post')->orderBy('latest_post','DESC')->paginate(15);

但这也给了我另一个错误

'订单子句'中的未知列'latest_post'

如何解决这个问题?

标签: phplaravel

解决方案


嗯。尝试这个

$topic = Post::orderBy('created_at','desc')->first()->join('topics', 'topics.id', '=', 'posts.topic_id')->first();

或在您的帖子模型中:

    public function Topic()
    {
        return $this->belongsTo(Topic::class, 'topic_id');
    }

要获取最后一个活动主题:

$topic = Post::orderBy('created_at','desc')->first()->Topic;

推荐阅读