Laravel:获取所有最后一个关联模型满足某些条件的模型

3
我有两个模型Post和Comment,我想获取所有最后一条评论是活动状态的帖子:
// Model Post
public function comments()
{
  return $this->hasMany('comments');
}

//Model Comment
public function post()
{
  return $this->belongsTo('post');
}

我尝试了这个解决方案:
public function lastComment()
{
 return $this->hasOne('comment')->latest()
}

在我的控制器中:

$postsWithLastActiveComment = Post::whereHas('lastComment', function($q){
  $q->where('active',1);
})->all();

但在这个解决方案中,如果最后一条评论不活跃,则会采取上一条评论。


请看:https://stackoverflow.com/a/50687657/4848587 - Jonas Staudenmeir
5个回答

2
我不确定是否有其他更简单的方法来解决这个问题,但也许你可以尝试使用子查询?"
$lastComment = Comment::select('active')
    ->whereColumn('post_id', 'posts.id')
    ->latest()
    ->limit(1)
    ->getQuery();

$posts = Post::select('posts.*')
    ->selectSub($lastComment, 'last_comment_is_active')
    ->having('last_comment_is_active', 1)
    ->get();

1

->latest() 仅按照创建时间对文章进行排序,因此要获取最新的评论,您需要使用 ->latest()->first()


未定义的方法 Illuminate\Database\Query\Builder::getRelated() 的调用。 - Mostafa Abedi
关系查询中不允许使用第一种方法。 - Mostafa Abedi
你之所以会收到getRelated错误,是因为你的Comments关系是HasMany而不是HasOne(尽管你只想要一个)。所以你可以这样写:$this->hasMany('comments')->latest()->first() - Matt Wohler

1
我觉得下面的代码应该可以工作!
public function comments()
{
  return $this->hasMany('comments');
}

public function lastComment()
{
  return $this->comments()->latest()->first();
}

1

Shouldn't this

$postsWithLastActiveComment = Post::whereHas('lastComment', function($q){
  $q->where('active',1);
})->all();

be

 $postsWithLastActiveComment = Post::whereHas('lastComment', function($q){
    $q->where('active',1);
 })->get();

0
根据您的问题,Post模型有许多评论。您想要从active为1且必须是最新id的帖子中获取评论。
获取最后一条评论如下所示:
public function lastComment()
{
    return $this->hasOne('comment')->latest()->take(1);
}

获取所有帖子,其中lastComment类似于以下内容。
$latestCommentPosts = Post::whereHas('lastComment')->get()

并且像下面这样过滤latestCommentPosts

$latestCommentPosts->where('active', 1)->get()

或者,您也可以通过以下查询一次性进行归档。

Post::whereHas('comments', function($q) { 
    $q->where('active', 1); 
})->get()

这样,您就可以获取所有最新的评论,并且其状态为1。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接