【问题标题】:Carbon divide records into weeks and monthsCarbon 将记录分为周和月
【发布时间】:2020-04-28 10:57:00
【问题描述】:

我有一个记录,我在其中获取过去 4 个月的时间戳(created_at、updated_at)数据。接下来,我想将此数据划分为按周和按月(过去 4 周和过去 4 个月)。

我正在尝试的是为每个月手动创建变量,然后编写 if 逻辑以将数据输入每个月。有什么功能已经做到了吗?

    // for student population - Last 4 months data
    $from = Carbon::now()->subMonth(4);

    $to = Carbon::now(); 

    $invoice =invoice::where('instructor_id', '=', $id)
    ->whereBetween('created_at',[$from,$to])->get();

    $week_1=$week_2=$week_3=$week_4=$month_1=$month_2=$month_3=$month_4=[];

    // write if logic and enter data for each week separately

【问题讨论】:

  • 您可以使用收集方法whereBetween 过滤$invoice 集合中每周和每月的数据,方法与从数据库中检索数据的方式相似。

标签: php laravel


【解决方案1】:

不,在 Eloquent 或 Carbon 中没有 function that already does it,afaik。

我建议循环浏览 Eloquent 集合。

这里给你一个提示:

$from = Carbon::now()->subMonth(4);
$to = Carbon::now(); 

$invoices = invoice::where('instructor_id', '=', $id)->whereBetween('created_at', [$from, $to])->get();

// ...

$invoicesLastWeek = $invoices->whereBetween('created_at', [
        Carbon::now()->subWeeks(1)->startOfWeek(),
        Carbon::now()->subWeeks(1)->endOfWeek()
    ]);

// ...

$invoicesTwoMonthsAgo = $invoices->whereBetween('created_at', [
    Carbon::now()->subMonths(2)->startOfMonth()),
    Carbon::now()->subMonths(2)->endOfMonth()
]);

// ...

我会循环并增加 ->subWeeks($i)->->subMonths($i)-> 的参数,并填充所需的变量。

我将首先开始设置每个 week 变量,以便我可以从集合中弹出该范围内的所有发票(用于性能)。然后对于每个 month 变量,我将添加 weekN + weekN+1 + weekN+2 + weekN+3 变量(并将它们从集合中弹出,以便我在每次都变得更小的集合上更快地循环)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-19
    • 2014-09-20
    • 1970-01-01
    • 2017-05-19
    • 1970-01-01
    • 2018-03-16
    • 2015-06-15
    • 1970-01-01
    相关资源
    最近更新 更多