php - Laravel hasMany 关系计数帖子上的喜欢和评论数

标签 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);

每个帖子都有评论和点赞。我最初只显示一些评论以避免大量加载。但我想显示每个帖子的总评论和点赞数。我该怎么做?

模型代码:

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();
}

注意:

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

更新

返回

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

更新

我如何返回数据

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

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

只需使用它,我就可以在 json 中获得我想要的所有数据。但我还想添加总计数。


更新

protected $appends = array('total_likes');

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

}

但出现错误:

 Unknown column 'likes.post_id'

错误

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)

最佳答案

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

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

还可以像这样设置计数条件

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

关于php - Laravel hasMany 关系计数帖子上的喜欢和评论数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20770284/

相关文章:

PHP Gearman 任务不返回 jobHandle

php - php 中的服务器端和客户端浏览器宽度和 Bootstrap 轮播问题

mysql - 升级后无法访问AWS RDS实例

mysql - 如何使用 Laravel 的 Eloquent 实现单表继承?

php - octobercms 任务调度不工作

php - 如何使用带有 laravel 的 Redis 和 Nodejs 广播消息

php - 按角色删除旧用户

mysql - 以html形式将空字符串更新为NULL

mysql order by count - 按值排序

MySQL 基于多种因素(位置、日期和时间)触发/检查 INSERT