关于php:Laravel组groupBy()雄辩的返回计数

Laravel Eloquent return count of each group with groupBy()

我想使用Laravel Eloquent进行groupBy()任务。我已经搜索了Internet,但并没有雄辩地找到任何东西。
有些人通过查询生成器使用groupBy()查询,例如此链接

但是我想创建如下样式的查询:

1
Task::select('id')->groupBy('category_id')->count();

此代码仅返回第一个category_id的计数。但我要计算所有category_id


本机集合替代(按php分组,而不是mysql)。当您已经将Collection作为变量分配时,这是一个不错的选择。当然,在大多数情况下,最佳化效果不及mysql分组。

1
$tasks->groupBy('category_id')->map->count();


您应该将计数添加到选择函数中,并使用get函数执行查询。

1
Task::select('id', \\DB::raw("count(id)"))->groupBy('category_id')->get();

\\DB::raw()函数可确保在不Laravel修改其值的情况下将字符串插入查询中。


我在模型中覆盖了count()方法。可能是这样的:

1
2
3
4
public function count($string = '*'){
    $tempmodel = new YourModel();
    return $tempmodel ->where('id',$this->id)->where('category_id',$this->category_id)->count($string);
}

这恰好给了我正在寻找的count()行为。


的身份为我工作

we need to select one column like 'category_id' or 'user_id' and then
count the selected column on get()

1
2
3
4
5
    Task::select('category_id')
           ->where('user_id',Auth::user()->id)
           ->groupBy(['category_id'])
           ->get()
           ->count();


更简单:

1
Task::select('id')->groupBy('category_id')**->get()**->count();

您可以执行以下操作:

1
return DB::table('offers')->select('*', DB::raw('count('.$field.') as total_count'))->groupBy($field)->get();