仅获取具有最新一条评论的帖子,该评论具有超过 5 个声誉

Get only posts with has latest one comment, which has more then 5 reputation

我有 $posts collection 个实例,我不会只获取有评论的帖子,而最新的评论有 5 个以上的声誉。我的 collection 实例与此类似

[
    [
        'id' => 1,
        'title' => 'Some title',
        'comments' => [
            [
                'id' => 1,
                'content' => 'some content',
                'reputation' => 5
            ],
            [
                'id' => 2,
                'content' => 'some content',
                'reputation' => 6
            ],
            ...
        ],
    ],
    ...
]

我的密码是

$posts = $posts->filter(function ($post, $key) {
    $isHasMoreFiveComments = false;
    foreach ($post['comments'] as $comment) {
        if ($comment['reputation'] > 5) {
            $isHasMoreFiveComments = true;
            break;
        }
    }
    return $isHasMoreFiveComments;
});

但我认为还有更好的解决方案。

我不确定你想从这里得到什么,但这可能对你有用吗?

bellow 将检索至少有 1 条评论且声誉为 5 及以上的帖子,并且它是按降序排列的。

$posts = Post::whereHas('comments')->with(['comments'=>function($q){
    $q->where('reputation', '>', 4); 
    $q->orderBy('id', 'desc');
}])->get();

注意:您必须在 Post 模型

中初始化 commments 的关系

例如:

class Post extends Model
{
    /**
     * Get the comments for the blog post.
     */
    public function comments()
    {
        return $this->hasMany('App\Comment');
    }
}

我在这里找到更好的解决方案代码

$posts = $posts->filter(function ($post, $key) {
    $comments = collect($post['comments']);
    return $comments->pluck('reputation')->max() > 5;
});

如果你想发表评价超过 5 的评论,那么 @Jesus Erwin Suarez 的答案是正确的。

但是如果你想得到另一个字段来检查 post 是否有评论的声誉超过 5,这将起作用:

// this will add an extra column `has_reputed_comments` in rows
$posts = Post::selectRaw('*, IF(EXISTS(SELECT * FROM comments where comments.post_id = posts.id AND comments.reputation > 5 ORDER BY id DESC), 1, 0) as has_reputed_comments')->get();

已更新

要过滤评论中提到的集合,您可以这样做:

// this will return filtered result by reputation greater than 5
$comments = $posts->comments->where('reputation', '>', 5);