gpt4 book ai didi

php - 使用 Laravel 每月接收数据

转载 作者:可可西里 更新时间:2023-11-01 00:55:05 24 4
gpt4 key购买 nike

我正在尝试创建一个显示每月数据的 morrisJS 折线图。所以我每个月都这样获取数据:

        $intakes = Intakes::whereYear('created_at', '=', 2018)
->orWhere(function ($query) {
$query->whereMonth('created_at', '=', 1)
->whereMonth('created_at', '=', 2)
->whereMonth('created_at', '=', 3)
->whereMonth('created_at', '=', 4)
->whereMonth('created_at', '=', 5)
->whereMonth('created_at', '=', 6)
->whereMonth('created_at', '=', 7)
->whereMonth('created_at', '=', 8)
->whereMonth('created_at', '=', 9)
->whereMonth('created_at', '=', 10)
->whereMonth('created_at', '=', 11)
->whereMonth('created_at', '=', 12);
})
->get();

但这会返回所有记录,从第 1 个月到第 12 个月。但是我想要的是每个月的数据,除了像这样创建多个变量之外可以实现吗?

          $intakesMonth1 = Intakes::whereYear('created_at', '=', 2018)
->whereMonth('created_at', '=', 1)
->get();

$intakesMonth2 = Intakes::whereYear('created_at', '=', 2018)
->whereMonth('created_at', '=', 2)
->get();

我希望我足够清楚并且有人知道更好的解决方案。

最佳答案

如果你想要 Eloquent 解决方案,请使用 whereMonth():

for($i = 1; $i < 13; $++) {
$intakes[$i] = Intakes::whereMonth('created_at', $i)->get();
}

您也可以获取一年的所有摄入量,然后使用 where() Laravel Collections 方法仅获取一个月的摄入量:

$oneMonthData = $collection->where('created_at', '>', Carbon::parse($someDateString)->startOfMonth())->where('created_at', '<', Carbon::parse($someDateString)->endOfMonth());

关于php - 使用 Laravel 每月接收数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48232123/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com