laravel - 如何在 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,
这是错误的输出,因为一个人对该帖子的评论不止一条。
解决方案
推荐阅读
- c# - 我可以在 CreateAssetMenu 中设置子文件夹的排序顺序吗?
- c++ - 读/写 UTF-8 输入
- reactjs - WebpackError:#95313 Gatsby 构建失败
- javascript - 如何在 Typescript 中键入对象键?
- r - 将一个值与多列匹配
- javascript - React 不会呈现它收到的最后一个钩子更新
- php - PHP:为函数调用指定一个变量名
- javascript - 根据前缀拆分字符串?
- java - 字符串数组 String [] 非 null 导致 ResultSet 中的 null 抛出 NullPointerException
- python - 使用代理连接 Python 库