【问题标题】:Laravel get topic that has last postLaravel 获取最后一篇文章的主题
【发布时间】:2019-11-12 11:21:40
【问题描述】:

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

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”

如何解决这个问题?

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    嗯。试试这个

    $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;
    

    【讨论】:

    • 这种情况下如果有新的帖子会重复主题
    猜你喜欢
    • 1970-01-01
    • 2015-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多