php Laravel hasMany 关系统计帖子的点赞数和评论数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20770284/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 03:32:35  来源:igfitidea点击:

Laravel hasMany relation count number of likes and comments on post

phpmysqllaraveleloquent

提问by majidarif

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.

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



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)

回答by Sachin Kumar

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

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

 $posts = App\Post::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();

回答by Anam

In your model place the following accessors:

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

Count total Likes:

计算总赞数:

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

 }

Count total comments:

统计评论总数:

From your description, i can see, you have retrieving the number of posts as comments

从你的描述中,我可以看到,你已经检索了作为评论的帖子数量

public function getTotalCommentsAttribute()
{
    return $this->hasMany('Post')->whereUserId($this->author_id)->count();    
}

Now, from your controller:

现在,从您的控制器:

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

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

// total Likes
var_dump( $post->total_likes );

回答by Mamun Rasid

Count comments for all blog posts in laravel

计算 Laravel 中所有博客文章的评论数

Step 1: Place this code inside your ‘Post' model.

第 1 步:将此代码放入您的“发布”模型中。

// Get the comments for the blog post.
public function comments()
{
    return $this->hasMany('App\Comment');
}

Step 2: Place this code inside your ‘PostController' controller.

第 2 步:将此代码放在您的“PostController”控制器中。

 $posts= Post::all();
 return view('home')->with('posts', $posts);

Step 3: Then count comments for all posts using the below code.

第 3 步:然后使用以下代码计算所有帖子的评论。

@foreach($posts as $row)
 {{$row->comments->count()}}
@endforeach

See details here: http://www.pranms.com/count-comments-for-all-blog-posts-in-laravel/

在此处查看详细信息:http: //www.pranms.com/count-comments-for-all-blog-posts-in-laravel/

回答by Adan Luna

Just single change to get results of the count

只需更改即可获得计数结果

In relation

在关系

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

In the view

在视图中

$post->getTotalLikesAttribute()