laravel chartjs日期跳过

问题描述 投票:0回答:1

谁能帮助我,请......我有数据库的活动成员,并希望显示在chartjs过去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

我的laravel代码

$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-172020-04-24 它的逻辑,但我想显示在图表天,当会员没有任何奖金,如 2020-04-23 不存在,因为会员没有奖金这一天,所以我需要在图表0中显示2020-04-23。

谁能帮帮我?

php laravel chart.js
1个回答
0
投票

我以为你的 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');
            });
© www.soinside.com 2019 - 2024. All rights reserved.