[英]Laravel hasMany relation count number of likes and comments on post
代码:
$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)
在模型中放置以下访问器:
计算喜欢总数:
public function getTotalLikesAttribute()
{
return $this->hasMany('Like')->whereUserId($this->author_id)->count();
}
计算总评论数:
从您的描述中,我可以看到,您已经获取了评论的帖子数
public function getTotalCommentsAttribute()
{
return $this->hasMany('Post')->whereUserId($this->author_id)->count();
}
现在,从您的控制器:
$post = Jumpsite::find($jid);
// total comments
var_dump( $post->total_comments );
// total Likes
var_dump( $post->total_likes );
您可以使用以下代码对关系模型结果进行计数。
$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();
计算laravel中所有博客文章的评论
第1步:将此代码放入“发布”模型中。
// Get the comments for the blog post.
public function comments()
{
return $this->hasMany('App\Comment');
}
第2步:将此代码放入“ PostController”控制器中。
$posts= Post::all();
return view('home')->with('posts', $posts);
步骤3:然后使用以下代码计算所有帖子的评论。
@foreach($posts as $row)
{{$row->comments->count()}}
@endforeach
在此处查看详细信息: http : //www.pranms.com/count-comments-for-all-blog-posts-in-laravel/
只需一次更改即可获得计数结果
关于
public function getTotalLikesAttribute(){
return $this->hasMany('Like')->where('author_id',$this->author_id)->count();
}
在视图中
$post->getTotalLikesAttribute()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.