My goal is to construct this data.
753
It works now, but it did so many queries to get what I need.
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