首页 > 解决方案 > 如何在 laravel eloquent 中的模型中按条件移动组

问题描述

我有一个帖子,我想知道帖子的评论数量,并想知道该帖子上不同用户的总数。

我得到了总评论数withCount(),但我被不同用户对该帖子发表评论的总数困住了。

我想使用groupBy,但是如果我想到以下代码的问题,如何在模型本身中做到这一点

public function TotalUsers() {
    return $this->hasMany(PostComment::class)
        ->select('user_id')
        ->groupBy('user_id');
}

public function TotalComments() {
    return $this->hasMany(PostComment::class)
        ->select('user_id');
}

post_comments表具有以下结构:


// Post table Structure
id,
user_id,
title,
slug,
content,
status,
created_at
updated_at

// Post Comment table Structure
id, 
user_id, 
post_id, 
comment,
created_at, 
updated_at

// User table Structure
id,
name,
email,
verified_email,
password,
refresh_token,
status,
created_at
updated_at

我在这两个函数中得到的结果与函数相同withCount()。即使同一个用户在同一个帖子上有多个评论。所以我认为groupBy是行不通的。

// 编辑 - 添加示例输出


total_comments_count: 907,
total_users_count: 907,

这是错误的输出,因为一个人对该帖子的评论不止一条。

标签: laravelgroup-byeloquent

解决方案


推荐阅读