Query count base on date groupBy Type – Laravel

My goal is to construct this data.

enter image description here

753

It works now, but it did so many queries to get what I need.

enter image description here

I’ve tried

$logs = BabyLog::where('babyId',$baby->id)->get();
$graphData = [];
foreach($logs as $i => $log){

    if(strtotime($log->updated_at) < strtotime(date('Y-m-d H:i:s'))){

        $logTime = strtotime($log->updated_at);
        $logDate = date('Y-m-d', $logTime );

        $logsOnThatDay = BabyLog::whereDate('updated_at', '=', $logDate)->where('babyId',$baby->id)->get();
        // dd($logsOnThatDay,$logDate);


        $pee      = 0;
        $poop     = 0;
        $feed     = 0;
        $medicine = 0;
        $sleep    = 0;



        foreach($logsOnThatDay as $j => $logOnThatDay){

                // dd($logOnThatDay);

            if($logOnThatDay->type == 'pee'){
                $pee++;
            }

            if($logOnThatDay->type == 'poop'){
                $poop++;
            }

            if($logOnThatDay->type == 'feed'){
                $feed++;
            }

            if($logOnThatDay->type == 'medicine'){
                $medicine++;
            }

            if($logOnThatDay->type == 'sleep'){
                $sleep++;
            }



        }


        $graphData[$logDate]['pee']      = $pee;
        $graphData[$logDate]['poop']     = $poop;
        $graphData[$logDate]['feed']     = $feed;
        $graphData[$logDate]['medicine'] = $medicine;
        $graphData[$logDate]['sleep']    = $sleep;
        

    }

    // dd($graphData);
}

I’ve tried to enhance it like this

$logs = BabyLog::whereDate('updated_at', '=', date('Y-m-d H:i:s'))
->whereIn('type', ['feed', 'pee', 'poop','medicine','sleep'])
->selectRaw('type, count(type) as count')
->groupBy('type')
->get()
->keyBy('type');

I’m kind of stuck now.

How do I optimize my query?

Answer

You can do a grouping on the PHP end:

$logs = BabyLog->where('babyId',$baby->id)->get()->groupBy(function ($log) {
   return $log->updated_at->format('y-m-d');
});

foreach($logs as $date => $logsOnThatDay) {
   // here on you can probably use the code you already have but this below might be shorter
   $graphData[$date] = $logsOnThatDay->reduce(function ($acc, $log) {
      if (array_key_exists($log->type, $acc)) { $acc[$log->type]++; }
       return $acc;
   }, [
      'pee' => 0,
      'poop' => 0,
      'feed' => 0,
      'medicine' => 0,
      'sleep' => 0,

   ]);
   
}

Leave a Reply

Your email address will not be published. Required fields are marked *