Laravel有许多关系计数在帖子上的喜欢和评论数量

maj*_*rif 8 php mysql laravel eloquent

代码:

$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);
Run Code Online (Sandbox Code Playgroud)

每个帖子都有评论和喜欢.我最初只显示一些注释以避免大负荷.但是我希望显示每篇文章的评论和喜欢的数量.我该怎么做呢?

型号代码:

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();
}
Run Code Online (Sandbox Code Playgroud)

注意:

This is an API. All will be returned as JSON.
Run Code Online (Sandbox Code Playgroud)

更新

回报

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
Run Code Online (Sandbox Code Playgroud)

更新

我如何返回数据

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

return Response::json(array(
   'data' => $posts
));
Run Code Online (Sandbox Code Playgroud)

只是通过使用我得到我想要的所有数据在json.但我也想增加总数.


更新

protected $appends = array('total_likes');

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

}
Run Code Online (Sandbox Code Playgroud)

但得到错误:

 Unknown column 'likes.post_id'
Run Code Online (Sandbox Code Playgroud)

错误

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)
Run Code Online (Sandbox Code Playgroud)

Ana*_*nam 9

在您的模型中放置以下访问器:

总数喜欢:

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

 }
Run Code Online (Sandbox Code Playgroud)

总评论数:

从您的描述中,我可以看到,您已将帖子数量检索为评论

public function getTotalCommentsAttribute()
{
    return $this->hasMany('Post')->whereUserId($this->author_id)->count();    
}
Run Code Online (Sandbox Code Playgroud)

现在,从您的控制器:

$post  = Jumpsite::find($jid);

// total comments
var_dump( $post->total_comments );

// total Likes
var_dump( $post->total_likes );
Run Code Online (Sandbox Code Playgroud)


sac*_*mar 8

您可以使用以下代码来计算关系模型结果.

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

并且还设置这样的计数条件

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

  • 这是正确答案。它避免加载整个集合以获取其元素的数量。 (2认同)