Support the ongoing development of Laravel.io →
Database Eloquent
Last updated 1 year ago.
0

Could you be so kind and show how do you use it in example. Thanks.

0

nhusby said:

I've been using Eloquent in a project outside of Laravel, and I needed pagination, so I built my own pager. I discovered that Eloquent doesn't really have a good solution to get the total rows found, especially when using eager loading, so I made this function.

I put a significant amount of effort into this, and I thought it might be of use to someone.

public static function calc_eloquent_found( $query_builder ){ $query = clone $query_builder->getQuery();

   $query->selectRaw('COUNT( DISTINCT '. $query_builder->getModel()->getKeyName() .' ) as total');
   $query->limit = null;
   $query->offset = null;

   //TODO: this needs more testing.
   if( $query->groups ){
       $subquery = $query->toSql();
       $chunks = explode( '?', $subquery );
       $bindings = $query->getBindings();      // do I need to strip out potential select bindings?

       $arr = [];
       foreach( $chunks as $i => $chunk ){
           $arr[] = $chunk;
           if( $bindings[ $i ] ){
               if( is_string( $bindings[ $i ] ) && !is_numeric( $bindings[ $i ] ) ){
                   $bindings[ $i ] = '"'. $bindings[ $i ] . '"';
               }
               $arr[] = $bindings[ $i ];
           }
       }
       $subquery = implode( '', $arr );

       $result = DB::select( DB::raw("SELECT SUM( sub.total) AS total FROM ($subquery) AS sub") )[0]['total'];

       return $result;
   }

   return $query->pluck('total');

}

Hi mate, thank you for your suggestion. Can you please let me know where did you added this function? Is it an eloquent class you extended ? If yes then which one?

Thank you.

0

Sign in to participate in this thread!

Eventy

Your banner here too?

nhusby nhusby Joined 5 May 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.