简体   繁体   中英

Laravel Eloquent return count of each group with groupBy()

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

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 .

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.

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

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.

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.

你可以这样做:

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

更简单:

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

Worked for me as

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

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

This works for me.

output:

return $email_trackers = EmailTracker::get()->groupBy('campaign_id')->map->count();
     
{
  "6": 2
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM