我想 groupBy()
使用Laravel当做大的任务。我在网上搜索了一下,没有找到任何有说服力的东西。 有些人将groupBy()查询与查询生成器一起使用,就像这个链接
但我想创建这样的查询风格:
Task::select('id')->groupBy('category_id')->count();
此代码仅返回第一个计数 category_id
. 但是我想数所有的 category_id
.
You should add the count to the select function and use the get function to execute the query.
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.
You can do something like this:
return DB::table('offers')->select('*', DB::raw('count('.$field.') as total_count'))->groupBy($field)->get();
More simple:
Task::select('id')->groupBy('category_id')**->get()**->count();
I overrode the count()
method in my model. Could be something like:
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.