[英]Laravel - Count by day of week
假设我有一个名为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 周...我出版了 2 本书等等。
数据集将返回如下内容:
$weekCount = [
'45' => 2,
'46' => 1,
'47' => 1,
'48' => 2
];
使用 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;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.