I'm trying to optimise my code wherein I generate stats over the last seven days.
Presently I'm using eloquent & querying counts for recorded data for each day, this causes me to make 7 seperate queries within a loop.
example:
// loop for number of days
for($i = 0; $i < $days; $i++){
// some logic to set comparitive unix times
$oldest = $newest - $dayDuration;
// count number of objects between oldest time and newest time
$counts[$i] = Object::where('objecttime','>',$oldest)
->where('objecttime','<',$newest)->count();
// more logic to set comparitive unix times
$newest = $newest - $dayDuration;
}
I know that one can group queries in sql using similar syntax as described here; what I would like to know is if it is possible to do the same using eloquent/fluent in Laravel, or is it only possible to do this using raw queries?
EDIT: I don't know if I need to clarify, but this is a Laravel 3 question.
Whenever you call a static method on your model class, it returns a Fluent query like
DB::table('yourmodeltable')->method
. If you keep that in mind, you will soon realize it's possible to do any query with Eloquent models.Now, to achieve greater performance, you can use SQLs DATE() function. My example below is untested, so feel free to correct it please.
This should print something like:
Edit:
The suggested approach above returns instances of Eloquent Model, which may seem weird, specially if you
var_dump($days)
. You can also use Fluent'slist()
method to achieve the same thing.