首页 > 解决方案 > 从日期开始的持续时间内的雄辩的单位总和

问题描述

我有一个表(项目),其中包含一个 start_date 和持续时间(以周为单位)和一个数字(progress_pw),关于每周可以实现多少进度单位

projects
+----+----------+--------+-----------+
| ID |start_date|duration|progress_pw|
+----+----------+--------+-----------+
|  1 |2018-06-15| 2      | 500       |
|  2 |2018-06-19| 4      | 120       |

我想按周汇总预计在给定周内使用的进度单元总数。

例如:

*从 6 月 11 日星期一开始的一周内 project.id 1 预计消耗 500 个单位

*从 6 月 18 日星期一开始的那一周,project.id 1 预计消耗 500 个单位,project.id 2 预计消耗 120 个单位,总消耗量为 620 个单位。

*从 2018 年 12 月 1 日开始的那一周(未来某个时间)没有活动项目,因此消耗了 0 个单位。

$i=0;$weeks=12;
while ($i < $weeks) {
    $thisweek = Carbon::now()->addWeeks($i)->startOfWeek()->format('Y-m-d');
    $requiredcap = DB::table('projects')->select(DB::raw("sum(progress_pw) as progress"))

    ->where('install_date', ">=", $thisweek) //<<< This is where im getting stuck!

    ->get();

    $capacity['label'][] = Carbon::now()->addWeeks($i)->startOfWeek()->format('d M');
    $capacity['required'][] = $requiredcap;
    $i++;
}

这背后的逻辑有什么指示吗?

标签: eloquent

解决方案


尝试这个:

$i = 0; $weeks = 12;
while ($i < $weeks) {
    $start = Carbon::now()->addWeeks($i)->startOfWeek();
    $end = (clone $start)->addDays(6);
    $requiredcap = DB::table('projects')
        ->select(DB::raw('sum(progress_pw) as progress'))
        ->whereBetween('start_date', [$start->toDateString(), $end->toDateString()])
        ->orWhere(function ($query) use ($start, $end) {
            $query->where('start_date', '<', $start->toDateString())
                ->where('end_date', '>=', $start->toDateString());
        })->first();
    $capacity['label'][] = $start->format('d M');
    $capacity['required'][] = $requiredcap->progress;
    $i++;
}

推荐阅读