Laravel Eloquent 使用 groupBy() 返回每个组的计数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38716716/
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
Laravel Eloquent return count of each group with groupBy()
提问by paranoid
I want to groupBy()
task using Laravel Eloquent. I have searched Internet and didn't find anything with eloquent.
some people used groupBy() query with Query Builder like this link
我想groupBy()
使用 Laravel Eloquent 完成任务。我在互联网上搜索过,没有找到任何雄辩的东西。有些人使用 groupBy() 查询和查询生成器这样的链接
But I want to create query like this style:
但我想创建这样的查询:
Task::select('id')->groupBy('category_id')->count();
This code just return only count of first category_id
. But I want count of all the category_id
.
此代码仅返回 first 的计数category_id
。但我想计算所有category_id
.
回答by Marek Gralikowski
Native Collection alternative (grouped by php, not mysql). It's a nice option when you have the Collection as variable already assigned. Of course is less optimal than mysql grouping in most cases.
本机集合替代方案(按 php 分组,而不是 mysql)。当您已将 Collection 作为变量分配时,这是一个不错的选择。在大多数情况下,当然不如 mysql 分组优化。
$tasks->groupBy('category_id')->map->count();
回答by Jerodev
You should add the count to the select function and use the get function to execute the query.
您应该将计数添加到 select 函数并使用 get 函数执行查询。
Task::select('id', \DB::raw("count(id)"))->groupBy('category_id')->get();
The \DB::raw()
function makes sure the string is inserted in the query without Laravel modifying its value.
该\DB::raw()
函数确保在 Laravel 不修改其值的情况下将字符串插入到查询中。
回答by Fjonan
I overrode the count()
method in my model. Could be something like:
我覆盖了count()
模型中的方法。可能是这样的:
public function count($string = '*'){
$tempmodel = new YourModel();
return $tempmodel ->where('id',$this->id)->where('category_id',$this->category_id)->count($string);
}
This gave me exactly the behavior of count()
I was looking for.
这正是count()
我正在寻找的行为。
回答by zain khalid
Worked for me as
对我来说有效
we need to select one column like 'category_id' or 'user_id' and then count the selected column on get()
我们需要选择一列,如“category_id”或“user_id”,然后在 get() 上计算所选列
Task::select('category_id')
->where('user_id',Auth::user()->id)
->groupBy(['category_id'])
->get()
->count();
回答by Mahmoud Zalt
You can do something like this:
你可以这样做:
return DB::table('offers')->select('*', DB::raw('count('.$field.') as total_count'))->groupBy($field)->get();
回答by Nacho
More simple:
更简单:
Task::select('id')->groupBy('category_id')**->get()**->count();