代码之家  ›  专栏  ›  技术社区  ›  Davit Zeynalyan

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

  •  -1
  • Davit Zeynalyan  · 技术社区  · 6 年前

    我有$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;
    });
    

    但我认为还有更好的解决办法。

    3 回复  |  直到 6 年前
        1
  •  1
  •   Jesus Erwin Suarez    6 年前

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

    commments Post

    class Post extends Model
    {
        /**
         * Get the comments for the blog post.
         */
        public function comments()
        {
            return $this->hasMany('App\Comment');
        }
    }
    
        2
  •  0
  •   Davit Zeynalyan    6 年前

    $posts = $posts->filter(function ($post, $key) {
        $comments = collect($post['comments']);
        return $comments->pluck('reputation')->max() > 5;
    });
    
        3
  •  0
  •   Aakash Tushar    6 年前

    @Jesus Erwin Suarez

    // 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);