Laravel hasMany relation count number of likes and comments on post

前端 未结 4 1860
刺人心
刺人心 2020-12-14 04:35

The code:

$posts = Jumpsite::find($jid)
            ->posts()
            ->with(\'comments\')
            ->with(\'likes\')
            ->with(\         


        
4条回答
  •  时光说笑
    2020-12-14 05:33

    You can use that following code for counting relation model result.

     $posts = App\Post::withCount('comments')->get(); foreach ($posts as $post) { echo $post->comments_count; }
    

    And also set condition with count like this

    $posts = Post::withCount(['votes', 'comments' => function ($query) { $query->where('content', 'like', 'foo%'); }])->get();
    

提交回复
热议问题