MySQL has a feature for getting the total number of records a query would return without a limit, SQL_CALC_FOUND_ROWS
. Does Laravel support this?
Currently I have to do it in two queries:
public function dataTable() {
$bookings = DB::table('bookings')
->limit(Input::query('iDisplayLength'))
->offset(Input::query('iDisplayStart'))
->get();
$count = $bookings = DB::table('bookings')
->count();
return Response::json([
'iTotalRecords' => $count,
]);
}
Not only will this be less efficient, but there's going to be a lot of redundant code once I add in all the ->where()
criteria.
For any complicated or vendor-specific queries, you generally have to pass the query directly with DB::raw()
, e.g.:
$bookings = DB::table('bookings')
->select(DB::raw('SQL_CALC_ROWS_FOUND ...
Refined what @giaour said.
$bookings = DB::table('bookings')
->select(array(DB::raw('SQL_CALC_FOUND_ROWS booking_id,name')))
->where('...')
->orWhere('...')
->take(10)
->skip(50)
->get();
$bookingsCount = DB::select( DB::raw("SELECT FOUND_ROWS() AS Totalcount;") );
After SQL_CALC_FOUND_ROWS you can fetch count by SQL_CALC_FOUND_ROWS();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With