mysql - Laravel Group 按月-年按天查询结果(如果日期不存在则显示所有日期)
问题描述
我有一张桌子exampleTable
:
+------------+--------+
| created_at | result |
+------------+--------+
| 2021-05-21 | 3 |
| 2021-05-21 | 4 |
| 2021-05-22 | 5 |
| 2021-05-23 | 6 |
| 2021-05-23 | 7 |
我想要结果:
+------------+--------+
| day | sumAll |
+------------+--------+
| 2021-05-01 | 0 |
| 2021-05-02 | 0 |
| 2021-05-03 | 0 |
....
| 2021-05-21 | 7 |
| 2021-05-22 | 5 |
| 2021-05-23 | 13 |
....
| 2021-05-29 | 0 |
| 2021-05-30 | 0 |
| 2021-05-21 | 0 |
这是我的查询:
$results = ExampleTable::select(
DB::raw("DATE_FORMAT(created_at,'%Y-%M-%d') as day"),
DB::raw('sum(result) as sumAll')
)
->whereMonth("created_at", '05')
->whereYear("created_at", '2021')
->groupBy('day')
->get();
但这不显示日期是否不存在。
如果数据不存在,我想要日期和结果值设置为 0 的日期值
解决方案
- 通过创建一个新集合
php artisan make:collection \\App\\Collections\\ExampleCollection
- 请执行下列操作:
<?php
namespace App\Collections;
use DatePeriod;
use Illuminate\Database\Eloquent\Collection;
class ExampleCollection extends Collection
{
public function withDefaults()
{
$date = $this->sortBy('day')[0]->day->firstOfYear();
$days = array_map(function($day) {
return $day->format('Y-m-d');
}, [...new DatePeriod("R11/{$date->toIso8601ZuluString()}/P1D")]); // e.g. 2021-01-01T00:00:00Z
$collection = array_fill_keys(array_fill_keys($days, []));
foreach($this as $item) {
$collection[$item->day->format('Y-m-d')] = $item;
}
return collect($collection);
}
}
- 在您的
ExampleTable
模型中添加以下内容:
public function newCollection(array $models = [])
{
return new ExampleCollection($models);
}
- 像这样使用它:
$results = ExampleTable::select(
DB::raw("DATE_FORMAT(created_at,'%Y-%M-%d') as day"),
DB::raw('sum(result) as sumAll')
)
->whereMonth("created_at", '05')
->whereYear("created_at", '2021')
->groupBy('day')
->get()
->withDefaults();
推荐阅读
- proxy - 如何通过代理网络使用 gcloud compute scp?
- web-scraping - 无法将 webbot 脚本转换为可执行文件
- multidimensional-array - VHDL无法初始化无符号向量数组
- laravel-5 - Mongodb和Mysql数据库的关系
- json - Unity JSON 与混合媒体二进制对象(如音频流缓冲区)
- java - 如何在 Spring MVC 应用程序中使用 OpenJDK 8 而不是 Oracle JDK 1.8?
- python - 如何通过python从mysql中检索零填充列?
- python - 将每个图像的尺寸导出到 Excel
- java - 在Java中获得所有可能组合的递归函数
- javascript - 获取所选电台的 3 个值 | JS