首页 > 解决方案 > 仅获取具有最新一条评论且声誉超过 5 条的帖子

问题描述

我有 $posts 集合实例,我不会只得到那些有评论的帖子,而最新的一条评论有更多的 5 名声。我的收藏实例与此类似

[
    [
        '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;
});

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

标签: phplaravellaravel-5laravel-5.5laravel-5.6

解决方案


我不确定你想在这里做什么,但可能这对你有用?

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

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

注意:您必须commmentsPost模型中初始化关系

前任:

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

推荐阅读