0

How can I get the total number of records for each of the grouped column(some_id) results generated in this eloquent query? (Answers generated using DB query builder or vanilla PHP also welcome).

$results = \App\MyModel::groupBy('some_id') ->whereNotNull('some_id') // some query here to get sum of each grouped column records ->get(); 

The desired result would be such that when I'm looping through the results, I can also have a field called for example totalRecords for each grouped results. i.e.

foreach($results as $result) { echo $result->totalRecords; } 
2
  • you can use method $result->count(), also in foreach loop based on your defined relation with other models, you can also do $result->relation_model->count Commented Jul 30, 2018 at 4:04
  • @ankitpatel not exactly what I'm looking form please see the edited question Commented Jul 30, 2018 at 4:12

3 Answers 3

2
$results = DB::table('your_table') ->select('some_column_name', DB::raw('count(some_id) as totalRecords')) ->whereRaw('some_id IS NOT NULL') ->groupBy('some_id') ->get(); 
Sign up to request clarification or add additional context in comments.

Comments

2

You can do like this :-

$results = \App\MyModel::select('*', DB::raw('count(some_id) as totalRecords')) ->groupBy('some_id') ->whereNotNull('some_id') ->get(); foreach ($results as $result) { echo $result->totalRecords; } 

2 Comments

Not exactly what I'm looking form please see the edited question
Updated answer!
0

Collection Provide itself count() method. But sometime once you fetch whole collection using get(). You can use count method on collection something like this:

$results = \App\MyModel::groupBy('some_id') ->whereNotNull('some_id') // some query here to get sum of each grouped column records ->get(); dd($results->count()); 

Also, If your data is not collection then Php array's provide you count method you can use that too:

dd(count($results)); 

I used dd method just for debuging purpose.That will show you result before actual output.

count() method of array will help you to count collection as well as sub collection or array of sub array.

Good luck !!!

3 Comments

Please see the accepted answer for your future needs.
Well Laravel providing Eloquant system and also providing count method then why we need to use DB query. I more prefer count method instead of raw query. But that's my personal thought.
Read on a concept called subqueries, that's what was needed here.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.