如何在Laravel中获取最近10周的数据

时间:2019-06-25 12:00:25

标签: sql laravel

我想获取过去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查询解决这个问题

1 个答案:

答案 0 :(得分:0)

我假设您的模型是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的更多信息。