如何使用Laravel获取最近7天每天注册的产品数量

问题描述 投票:0回答:2

我有一张产品桌子。在此表中,我有一列列出了产品的卡卡斯特价格。

[我当时正在查看Carbon,想在我的Laravel应用程序中实现一种方法,该方法可以显示最近7天的产品数量。

在Java中,我使用此方法:

public Date getSevenDays() {
        Calendar cal = Calendar.getInstance(); 
        cal.set(Calendar.DAY_OF_MONTH, cal.get(Calendar.DATE) - 7);
        Date lastSevenDays = cal.getTime();
        return lastSevenDays;
    }

我该如何使用Carbon进行调整,以便他退还最近7天注册的产品数量?返回将是这样的数组:

[6,4,18,11,5,16,7]
laravel php-carbon
2个回答
0
投票

尝试这样的事情:

$from = Carbon::now()->subDays(7);
$to = Carbon::now();
$products = Product::whereBetween('created_at', [$from, $to]) ->lists('id')->toArray();

该代码未经测试。


0
投票

为什么不只获取最近7天的所有记录并按日期分组

use Carbon\Carbon;

$productsByDay = Product::where('created_at', '>=', Carbon::now()->subDays(7))
                ->groupBy('date')
                ->orderBy('date', 'DESC')
                ->get([
                DB::raw('DATE(created_at) as date'),
                DB::raw('COUNT(*) as "products"')
])->pluck('products','date')->toArray();
//I recommend key by date, so that if you have no products on a date, you still have the dates in order.

//you can pass timezone in now() method of carbon, if you timezone is different than the timezone stored in DB
© www.soinside.com 2019 - 2024. All rights reserved.