gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 06:31:36 25 4
gpt4 key购买 nike

代码:

$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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com