Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
786 views
in Technique[技术] by (71.8m points)

php - 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)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

 $posts = AppPost::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();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...