Home > Software engineering >  optimize laravel eloquent relationship
optimize laravel eloquent relationship

Time:12-19

i want to check the scheduling of a staff member for whole month. currently i m iterating through each date of a month, and then each hours in that specific day. and when i saw the debugger i got 1000 queries. is there any optimized way to fetch all the scheduling from the staff table, stored in a variable and then check my condition through that array rather than hitting the server each time and getting data from db

#iterating each day for whole month
        foreach ($dates as $key => $today) {
            $daily = []; $daily[0] = 'fullyAvailable';
            $i = 1;

            #iterating each hours, 17 hours a day (17 iteration)
            for ($time = $opening_time; $time <= $closing_time; $time  ) {
                $unit = $inst->instructor->hourlySubscribedUnit($today, date("H:00:00", mktime($time)), date("H:00:00", mktime($time   1)));

                if (isset($unit)) {

                    $daily[0] = 'fullyScheduled';
                    $daily[$i] = $unit->unit_type;
                    $totalScheduledCount  ;

                }elseif ($inst->instructor->timings($today)->count() > 0) {
                    $daily[0] = 'fullyAbsent';
                    break;

                } else {
                    $daily[$i] = 'available';
                    $totalAvailableCount  ;
                }
                $i  ;
            }
            $monthly[$key] = $daily;
        }


#and this is the relationship defined inside the staff model

   {
      return $this->hasMany(SubscriptionUnits::class, 'instructor_id')
      ->whereDate('date', $date)
      ->when($from && $to, function($query) use ($from, $to){
         return $query->whereTime('from', '>=', $from)->whereTime('to', '<=', $to);
      })->select('unit_type')->first();
   }`

CodePudding user response:

I think what you should do is eager load the staff member. you can check how to do this in the laravel documentation

CodePudding user response:

You can use chunk(), it functions to divide lots of data and manage data piece by piece to reduce memory usage, of course the performance is getting better.

for more on other overflow posts. laravel-chunk-method-using-eloquent

  • Related