简体   繁体   中英

How to get count of each result

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. ie

foreach($results as $result) {
    echo $result->totalRecords;
}

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;
}
$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();

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 !!!

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