php – 如何在sql中按月过滤

如何使用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();

您需要自己进行测试,以确定哪种更快或最有效.此外,一些数据库不允许多个分组(我们在这里没有,但您可能想要添加)而不修改其配置,因此除非您使用大量数据集,否则我的个人头奖将是原始方法.

点赞