简体   繁体   中英

Laravel - Count by day of week

Let's say I have this database table called 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  |
+----+-----------+-------------+

How would I use Laravel's Eloquent to group by week of year so that on week 45... I published 2 books and so on.

And dataset would return something like:

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

Use mysql WEEK(timestamp) :

Group by week number with year:

$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;
    });

Group by week number without year:

$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;
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM