有人能帮帮我吗..。我有包含活动成员的数据库,并希望在图表中显示最后7天的数据。
id member_id bonus created_at
1 1 3 2020-04-16
2 1 3 2020-04-17
3 1 7 2020-04-18
4 1 5 2020-04-19
5 1 15 2020-04-20
6 1 10 2020-04-21
7 1 9 2020-04-22
8 1 11 2020-04-24我的拉拉密码
$chart = charts::where('member_id', Auth::user()->id)->orderBy('id', 'asc')->where('created_at', '>=', \Carbon\Carbon::today()->subDays(7))->get();
$bonus = [];
foreach ($charts as $index => $count) {
$bonus[] = [$count->bonus];
}
return view('index', ['bonus' => $bonus]);问题是在图表中,因为显示从2020-04-17到2020-04-24的数据是合乎逻辑的,但我也想在图表中显示成员没有任何奖金的日子--例如, 2020-04-23 不存在,因为成员这一天没有奖金,所以我需要在2020-04-23的图表0中显示。
有人能帮我吗?
发布于 2020-04-24 02:21:08
我假设您的created_at列是timestamp (为该示例添加格式)
public function index()
{
$start = Carbon::today()->subDays(7);
$end = Carbon::yesterday();
$activities = Activity::where('member_id', Auth::user()->id)
->where('created_at', '>=', Carbon::today()->subDays(7))
->get(['bonus', DB::raw("DATE_FORMAT(created_at,'%Y-%m-%d') as date")])
->pluck('bonus', 'date');
$dates = $this->generateDates($start, $end); // you fill zero valued dates
return $dates->merge($activities); // overwrite your bonuses with the zero values
}
public function generateDates(Carbon $startDate, Carbon $endDate, $format = 'Y-m-d')
{
$dates = collect();
$startDate = $startDate->copy();
for ($date = $startDate; $date->lte($endDate); $date->addDay()) {
$dates->put($date->format($format), 0);
}
return $dates;
}格式化日期
$formattedDates = $dates->merge($activities)
->keys()
->transform(function ($date) {
return Carbon::parse($date)->format('d F');
});https://stackoverflow.com/questions/61399743
复制相似问题