Laravel hasMany relation count number of likes and comments on post

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

The code:

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


        
相关标签:
4条回答
  • 2020-12-14 05:19

    In your model place the following accessors:

    Count total Likes:

     public function getTotalLikesAttribute()
     {
        return $this->hasMany('Like')->whereUserId($this->author_id)->count();
    
     }
    

    Count total comments:

    From your description, i can see, you have retrieving the number of posts as comments

    public function getTotalCommentsAttribute()
    {
        return $this->hasMany('Post')->whereUserId($this->author_id)->count();    
    }
    

    Now, from your controller:

    $post  = Jumpsite::find($jid);
    
    // total comments
    var_dump( $post->total_comments );
    
    // total Likes
    var_dump( $post->total_likes );
    
    0 讨论(0)
  • 2020-12-14 05:27

    Count comments for all blog posts in laravel

    Step 1: Place this code inside your ‘Post’ model.

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

    Step 2: Place this code inside your ‘PostController’ controller.

     $posts= Post::all();
     return view('home')->with('posts', $posts);
    

    Step 3: Then count comments for all posts using the below code.

    @foreach($posts as $row)
     {{$row->comments->count()}}
    @endforeach
    

    See details here: http://www.pranms.com/count-comments-for-all-blog-posts-in-laravel/

    0 讨论(0)
  • 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();
    
    0 讨论(0)
  • 2020-12-14 05:40

    Just single change to get results of the count

    In relation

     public function getTotalLikesAttribute(){
        return $this->hasMany('Like')->where('author_id',$this->author_id)->count();
    }
    

    In the view

    $post->getTotalLikesAttribute()
    
    0 讨论(0)
提交回复
热议问题