douhuiqi3855 2019-07-01 20:06
浏览 72

Laravel得到了最后一篇文章的主题

I'm trying to do that , get list of topics order by who has new post so I create a relation in topic model like that

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

then I used the query like that

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

but it's giving me an error

Collection::render does not exist

so I change the sort to orderBy like that

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

but this also gives me another error

Unknown column 'latest_post' in 'order clause'

how can solve this issue?

  • 写回答

1条回答 默认 最新

  • doushu5805 2019-07-01 23:11
    关注

    Hmmm. Try this

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

    Or in your post model:

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

    To get the last active topic:

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

报告相同问题?

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向