lundi 15 mars 2021

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?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire