获取最近评论过的帖子
Fetch posts that most recently have been commented on
我正在尝试获取最近评论过的 post。但它根本 return 什么都没有。
我有一个具有此关系的 Post
模型
public function comments(){
return $this->morphMany(Comment::class, 'commentable');
}
和 ofc Comment
具有以下关系的模型:
public function commentable()
{
return $this->morphTo();
}
我正在尝试 return 来自视图编辑器的最新 post:
public function compose(View $view)
{
$view->with(['latestCommentedPost' =>
$this->post->select(['title', 'slug'])->with(['comments' => function($q){
return $q->latest()->take(6)->get();
}])
]);
}
但是$latestCommentedPost
是空的??
预期结果
获取 6 post 个最新评论。
按最近的评论排序,需要使用commentable
或comments
table中的created_at
。他们来自不同的 tables.
你需要左加入一个 commenttable
,它有 max created_at
,所以你可以按最近的评论排序。
public function compose(View $view)
{
$view->with(['latestCommentedPost' =>
$this->post->select(['posts.title', 'posts.slug'])
->leftjoin('commentable', function($join) {
$join->on('commentable.commentable_id', '=', 'posts.id')
->where('commentable.commentable_type', 'App\Post')
->latest()->limit(1);
})->latest('commentable.created_at')
->take(6)
->with(['comments' => function($q){
return $q->latest()->take(6)->get();
}])->get()
]);
}
我正在尝试获取最近评论过的 post。但它根本 return 什么都没有。
我有一个具有此关系的 Post
模型
public function comments(){
return $this->morphMany(Comment::class, 'commentable');
}
和 ofc Comment
具有以下关系的模型:
public function commentable()
{
return $this->morphTo();
}
我正在尝试 return 来自视图编辑器的最新 post:
public function compose(View $view)
{
$view->with(['latestCommentedPost' =>
$this->post->select(['title', 'slug'])->with(['comments' => function($q){
return $q->latest()->take(6)->get();
}])
]);
}
但是$latestCommentedPost
是空的??
预期结果
获取 6 post 个最新评论。
按最近的评论排序,需要使用commentable
或comments
table中的created_at
。他们来自不同的 tables.
你需要左加入一个 commenttable
,它有 max created_at
,所以你可以按最近的评论排序。
public function compose(View $view)
{
$view->with(['latestCommentedPost' =>
$this->post->select(['posts.title', 'posts.slug'])
->leftjoin('commentable', function($join) {
$join->on('commentable.commentable_id', '=', 'posts.id')
->where('commentable.commentable_type', 'App\Post')
->latest()->limit(1);
})->latest('commentable.created_at')
->take(6)
->with(['comments' => function($q){
return $q->latest()->take(6)->get();
}])->get()
]);
}