Laravel 5.5中如何实现年份与月份双列范围数据查询?
解决Laravel查询年份范围与对应月份范围的问题
嘿,我明白你的需求了——原来的查询只锁定了单个年份,现在要扩展成年份在$from到$to之间,同时对应年份的月份也要符合范围对吧?这里要注意一个容易踩的坑:如果年份跨了多个,直接用whereBetween处理月份会出错(比如从2022年10月到2023年2月,月份范围10到2在数据库里是不成立的),所以得分情况构建查询条件。
正确的查询代码
$from = $request->year_from; $to = $request->year_to; $month_from = $request->month_from; $month_to = $request->month_to; $param = $request->get('parameters_id', []); $search = Centrals::whereIn('parameters_id', $param) ->where('type', 'Monthly') // 核心:分三种情况筛选年份和月份 ->where(function($query) use ($from, $to, $month_from, $month_to) { // 1. 介于$from和$to之间的年份,所有月份都符合条件 if ($from < $to) { $query->whereBetween('year', [$from + 1, $to - 1]); } // 2. 等于起始年份$from,月份要大于等于$month_from $query->orWhere(function($q) use ($from, $month_from) { $q->where('year', $from) ->where('months_id', '>=', $month_from); }); // 3. 等于结束年份$to,月份要小于等于$month_to $query->orWhere(function($q) use ($to, $month_to) { $q->where('year', $to) ->where('months_id', '<=', $month_to); }); }) // 按年份和月份排序,结果更直观 ->orderBy('year') ->orderBy('months_id') ->get();
代码说明
- 用闭包嵌套的
where来组合多条件,避免逻辑混乱; - 分三种情况处理:
- 如果起始年份小于结束年份,中间的所有年份的所有月份都纳入结果;
- 起始年份只保留月份大于等于
$month_from的记录; - 结束年份只保留月份小于等于
$month_to的记录;
- 额外添加了
orderBy('months_id'),让同一年的结果按月份顺序排列,可读性更好。
如果你的场景中年份一定是同一年(即$from == $to),那可以简化成更简单的写法:
$search = Centrals::whereIn('parameters_id', $param) ->where('type', 'Monthly') ->where('year', $from) ->whereBetween('months_id', [$month_from, $month_to]) ->orderBy('months_id') ->get();
内容的提问来源于stack exchange,提问作者RAVI BANGKIT NUR ZIKRILLAH
相关产品推荐
相关产品推荐

