Laravel-按星期几计算

时间:2019-12-14 23:22:39

标签: php laravel

假设我有一个名为books的数据库表:

+----+-----------+-------------+
| id | bookTitle | publishedOn |
+----+-----------+-------------+
| 1  | Red Rose  | 2019-09-21  |
+----+-----------+-------------+
| 2  | Dark Fury | 2019-09-22  |
+----+-----------+-------------+
| 3  | Morbid    | 2019-10-01  |
+----+-----------+-------------+
| 4  | Dark      | 2019-11-14  |
+----+-----------+-------------+
| 5  | Route A   | 2019-11-15  |
+----+-----------+-------------+

我将如何使用Laravel的Eloquent对一年中的每一周进行分组,以便在第45周...我出版了两本书,依此类推。

数据集将返回类似的内容

$weekCount = [
  '45' => 2,
  '46' => 1,
  '47' => 1,
  '48' => 2
];

1 个答案:

答案 0 :(得分:1)

使用mysql WEEK(timestamp)

按周编号和年份分组:

$weekCount = [];
Book::selectRaw('WEEK(publishedOn) AS publishedWeek, COUNT(id) AS booksCount')
    ->where(...)
    ->groupBy("publishedWeek")
    ->get()
    ->map('publishedWeek', function($item) use ($weekCount) {
        $weekCount[$item->publishedWeek] = $item->booksCount;
    });

按星期编号而不包含年份

$weekCount = [];
Book::selectRaw("CONCAT(YEAR(publishedOn), '/', WEEK(publishedOn)) AS publishedWeek, COUNT(id) AS booksCount")
    ->where(...)
    ->groupBy("publishedWeek")
    ->get()
    ->map('publishedWeek', function($item) use ($weekCount) {
        $weekCount[$item->publishedWeek] = $item->booksCount;
    });