Home > other >  Avoid unuseful doble query laravel
Avoid unuseful doble query laravel

Time:11-11

I have a question for you!

I got my table with data structure like this:

acktime temperature
2021-10-30 14:16:38 15.12
2021-10-30 14:20:12 15.14
a lot of data in the same day
2021-10-31 10:16:38 13.16
2021-10-31 10:20:12 14.12

I have my model RawData and I create a collection instance with:

$mydata = rawData::select('acktime')->OrderBy('acktime', 'asc')->get();

Now I have to find how much days there's in and I found it in this way:

    foreach ($mydat as $value) {
        $ackday = Carbon::parse($value['acktime'])->format('Y-m-d');
        
        if ($tempDay != $ackday){
            Log::info('foun a new day! '.$ackday);
            $daystoreport[] = $ackday; 
            $tempDay = $ackday;
        }
    }

I got my $daystoreport array with the days found in the db

Now I need to take handle $mydata day per day and for the moment I did it with:

    $onedayData = rawData::whereDate('acktime', $daystoreport[0])
                    ->get();

But this make me an unuseful query cause, I have already get all data from the table before ($mydata)...

Unfortunatly I can't do something like this:

for(i=0;i=length of the array; i  ){    
$onedayData = $mydata->whereDate('acktime', $daystoreport[i]);
..do some stuff
}

Any suggestions?

CodePudding user response:

If I am not misunderstanding what you are trying to do, you could simply group your data by the day and then perform your actions on the respective collections:

RawData::all()
    ->groupBy(function (RawData $item) {
        // Format the time to a day string without time and group your items by that day
        return $item->acktime->format('Y-m-d');
    })
    ->each(function (Collection $day) {
        // Do day-based stuff in here
    });

Optionally, you can also group your days already in the database query

  • Related