sql - 如何在 Laravel 中获取过去 10 周的数据
问题描述
我想获取最近 10 周的数据
我的意思是我有一个表,其中包含已售出的产品我想排列数据,以便输出应该是
第 1 周:[product_1,product_2, ....] 第 2 周:[product_9,product_10, ....]
等等
我尝试了下面的代码来一天一天地得到它
DB::raw("SELECT week(order_invoice.delivery_date) week_id,
SUM( IF(weekday(order_invoice.delivery_date) = 1, 1, 0) as day_1 ),
SUM( IF(weekday(order_invoice.delivery_date) = 2, 1, 0) as day_2),
SUM( IF(weekday(order_invoice.delivery_date) = 3, 1, 0) as day_3),
SUM( IF(weekday(order_invoice.delivery_date) = 4, 1, 0) as day_4),
但我认为 70 天是错误的
我如何用 laravel 甚至 sql 查询来解决这个问题
解决方案
我假设你的模型是OrderInvoice
. 为了使其正常工作,请确保在OrderInvoice
模型中,您将delivery_date
其作为protected $dates
数组的一部分,以便 Carbon 自动解析属性。
$invoices = OrderInvoice::whereDate('delivery_date', >=, today()->startOfWeek()->subWeeks(10))->get(); // You can drop startOfWeek if you don't need it.
$weekData = [];
foreach ($invoices as $invoice) {
$w = $invoice->delivery_date->week; // use the week number as our array key
$weekData[$w][] = $invoice;
}
var_dump($weekData);
https://laravel.com/docs/5.8/queries#where-clauses有关whereDate
.
https://carbon.nesbot.com/docs/了解更多信息Carbon
。
推荐阅读
- javascript - 更改媒体查询
- excel - 将宏复制到新生成的工作簿
- c - 从c中的键盘获取字符时出现多字符警告
- java - adview导致android studio中的依赖项冲突
- java - SpatialFPStruct、RPR fom、netn2_2010 FOM 的问题。应该如何实施?
- mongodb - 带有嵌套集合的 Mongoose 聚合
- java - 为什么android代码中的这段java这么慢?
- java - 仅读取大小数组倍数的特殊输入流
- git - 如何将我的 bitbucket 项目复制到另一个 bitbucket 服务器
- .net-core - 使用 .netcore 从 Web api 获取 JSON 数据