Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel hasMany relation count number of likes and comments on post

The code:

$posts = Jumpsite::find($jid)
            ->posts()
            ->with('comments')
            ->with('likes')
            ->with('number_of_comments')
            ->with('number_of_likes')
            ->where('reply_to', 0)
            ->orderBy('pid', 'DESC')
            ->paginate(10);

Each post has a comment and likes. I only display a few of the comments initially to avoid large loads. But I want to show how many the total comments and likes for each post. How do I do this?

Model code:

public function likes()
{
    return $this->hasMany('Like', 'pid', 'pid');
}

public function comments()
{
    return $this->hasMany('Post', 'reply_to', 'pid')->with('likes')->take(4);
}

public function number_of_likes()
{
    return $this->hasMany('Like', 'pid', 'pid')->count();
}

Note:

This is an API. All will be returned as JSON.

update

The return

Post
    author_id
    message
    Comments(recent 4)
        user_id
        message
        post_date
        Number_of_likes
    Likes
        user_id
    Number_of_total_comments
    Number_of_total_likes

update

How I return the data

$posts  = $posts->toArray();
$posts  = $posts['data'];

return Response::json(array(
   'data' => $posts
));

Just by using that I get all the data i want in the json. But I also want to add the total counts.


update

protected $appends = array('total_likes');

public function getTotalLikesAttribute()
{
   return $this->hasMany('Like')->whereUserId($this->uid)->wherePostId($this->pid)->count();

}

but getting the error:

 Unknown column 'likes.post_id'

error

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'likes.post_id' in 'where clause' (SQL: select count(*) as aggregate from `likes` where `likes`.`deleted_at` is null and `likes`.`post_id` = 4 and `pid` = 4 and `uid` = 1)
like image 895
majidarif Avatar asked Dec 25 '13 07:12

majidarif


3 Answers

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 );
like image 180
Anam Avatar answered Nov 07 '22 01:11

Anam


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();
like image 26
Sachin Kumar Avatar answered Nov 07 '22 00:11

Sachin Kumar


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/

like image 2
Mamunur Rashid Avatar answered Nov 06 '22 23:11

Mamunur Rashid