如果你不想空記錄添加到數據庫中缺少日期
這將是頭痛這樣的:
$dates = [
'2016-12-01',
'2016-12-02',
...
'2016-12-31'
];
$records = Step::whereIn('date', $dates)
->where('user_id', Auth::id())
->get();
$steps = [];
$dates = array_flip($dates); // flipping array like: ['2016-12-01' => 0, '2016-12-02' => 1, ...]
foreach($records AS $record) { // iterating records
$steps[] = $record; // collecting records
unset($dates[$record->date]); // removing date that has record for that day
}
$dates = array_flip($dates); // flipping back: [0 => '2016-12-01', ...]
foreach($dates as $date) { // iterating dates that do not have data in db and creating model objects from them
// creating missing record "on the fly"
$Step = new Step([
'date' => $date,
'user_id' => Auth::id(),
'steps' => 0
]);
$Step->save();
$steps[] = $Step; // adding model instance to resulting array
}
usort($steps, function($a, $b) { // sorting array of steps by date
if(strtotime($a->date) > strtotime($b->date)) return 1;
if(strtotime($a->date) < strtotime($b->date)) return -1;
return 0;
});
所以我的建議是有一些控制檯命令(/app/Console/Commands/
)將每晚處理並確保所有記錄一致。
我的意思是創建一些後臺批處理過程,如果用戶沒有該日期的記錄,將會「關閉一天」並在數據庫中創建一些記錄。
這個建議簡化了一切,所以你的控制器只會像往常一樣得到數據,而不需要任何額外的計算,迭代等。