【问题标题】:How to count in laravel from different table如何从不同的表中计算laravel
【发布时间】:2019-02-23 05:59:12
【问题描述】:

嘿,我正在制作数据表,以显示登录并发布该帖子的用户对我的帖子有多少评论,但我遇到了一些错误,它只检索了 1 条但实际上我得到了 26 条评论,我不知道为什么。

在我的控制器中:

public function getCountComment()
{
    $user = Auth::user();
    return $all_count = $user->post()
        ->withCount('comment_to_post')
        ->take(5)->get();
}

模型comment.php

public function comment_to_post()
{
    return $this->belongsTo('App\Post','id_user');
}

我有 26 条评论,但它只检索到 1 条评论计数。希望你们能帮帮我

“comment_to_post_count”:1

【问题讨论】:

  • 您可以尝试删除查询中的 take(5)。
  • take 5 将限制帖子数量而不是 cmets 数量
  • 仍然只有 1 次检索

标签: mysql laravel count model controller


【解决方案1】:

你应该试试这个:

public function getCountComment()
{
    $user = Auth::user();
    $all_count = $user->post()
        ->withCount('comment_to_post')
        ->count();
    return $all_count;
}

【讨论】:

    【解决方案2】:

    我在我的代码中做过这样的事情——希望对你有帮助

    public function getCountComment()
    {
        $user = Auth::user();
        $posts = $user->posts();
    
        foreach ($posts as $key => $value) {
            $posts[$key]->post_comments_count = PostComment::where('post_id', $value->id)->count(); 
        }
        return $posts;
    }
    

    【讨论】:

      【解决方案3】:

      删除 take(5) 方法(限制)可能会修复它..

      【讨论】:

        猜你喜欢
        • 2016-06-25
        • 2021-10-19
        • 1970-01-01
        • 1970-01-01
        • 2015-08-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多