Laravel hasMany relation count number of likes and comments on post

前端 未结 4 1886
刺人心
刺人心 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 );
    

提交回复
热议问题