gpt4 book ai didi

php - sql中如何按月过滤

转载 作者:可可西里 更新时间:2023-11-01 07:38:22 25 4
gpt4 key购买 nike

如何使用sql查询优化我的代码

$collection->filter(function ($item) use ($i) {
return $item->created_at->month == $i->month;
})->count();

我希望在 sql 中过滤而不是集合上的过滤函数,这样它可以更快

这里是函数:

$data = [];
switch ($range) {
//monthly
case self::$timeRanges[0]:
for ($i = Carbon::now()->copy()->subYear()->endOfMonth(); $i <= Carbon::now()->subMonth()->endOfMonth(); $i->addMonths(1)) {
$data[$i->month] = $collection->filter(function ($item) use ($i) {
return $item->created_at->month == $i->month;
})->count();
}
break;
//weekly
case self::$timeRanges[1]:
$collection = $collection->where('created_at', '>=', Carbon::now()->subWeek()->endOfWeek()->subWeeks(5))->where('created_at', '<=', Carbon::now()->subWeek()->endOfWeek());
for ($i = Carbon::now()->copy()->subWeek()->endOfWeek()->subWeeks(5); $i <= Carbon::now()->copy()->subWeek()->endOfWeek(); $i->addWeeks(1)) {
$data[$i->weekOfMonth] = $collection->filter(function ($item) use ($i) {
return $item->created_at->weekOfYear == $i->weekOfYear;
})->count();
}
break;
}
return ($data);

感谢您的帮助,祝您有愉快的一天!

最佳答案

只是为了扩展@Elie 的回答,您甚至不需要使用原始查询。 Laravel 完美地满足了日期条件,并且在 Queries 上有很好的记录。页面。

$desiredMonth = 12;

Model::whereMonth('created_at', $desiredMonth)->get();

但是,这并不能完全回答手头的问题。我们需要做的是检索所有相关结果,然后对检索到的结果按月进行过滤。我相信通过从 SQL 检索所有结果然后按原样对它们进行过滤来执行此操作会更加高效和快速,但迭代代码更少:

$collection = Model::whereYear(2018)->get();

$months = $collection->groupBy(function ($item, $key) {
return $item->created_at->month;
});

$months->toArray();

[
'1' => [[...],[...],[...]],
'2' => [[...],[...],[...]],
'3' => [[...],[...],[...]],
'4' => [[...],[...],[...]],
'5' => [[...],[...],[...]],
'6' => [[...],[...],[...]],
'7' => [[...],[...],[...]],
'8' => [[...],[...],[...]],
'9' => [[...],[...],[...]],
'10' => [[...],[...],[...]],
'11' => [[...],[...],[...]],
'12' => [[...],[...],[...]],
]

此外,如果您坚持使用 SQL 进行过滤,您可以执行 groupBy:

Model::groupBy(\DB::raw('MONTH(created_at) as month'))->get();

您需要自行测试哪个更快或至少最有效。此外,某些数据库不允许在不修改其配置的情况下进行多个分组(我们这里没有,但您可能想添加),因此我个人的一等奖将是原始方法,除非您正在处理庞大的数据集。

关于php - sql中如何按月过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53258362/

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