php - 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'
如何解决这个问题?
解决方案
嗯。尝试这个
$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;
推荐阅读
- kotlin - 无法加载 AndroidJUnit4 的委托运行程序“androidx.test.internal.runner.junit4.AndroidJUnit4ClassRunner”
- continuous-integration - 如何仅在 GitlabCi 运行器中的 HEAD 提交时运行管道?
- laravel - 数据表显示分页器链接下方的空格
- c# - Intel MKL LAPACKE_dsyevd with n > 32766 --> 没有足够的内存在 LAPACKE_dsyevd 中分配工作数组
- http - 使用 AREST 框架在 kotlin 中创建带有请求正文的 GET 方法
- opencart - 我的 opencart 结帐页面显示,内部服务器错误
- matlab - 将 DICOM 文件堆叠成一个多切片系列
- javascript - Android模拟器上的React-Natiove错误“null不是对象(评估'blob.data')readAsText”
- java - 如何为 java.awt.Color 制作 switch 语句
- r - 使用R中的标题进行点到线插值