首页 > 解决方案 > 如何在 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 查询来解决这个问题

标签: sqllaravel

解决方案


我假设你的模型是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


推荐阅读