本文介绍在 laravel 中使用 eloquent 或 query builder 实现 sql 的 group by + having 逻辑,以统计每日预约数并仅返回数量超过指定阈值(如 $max)的日期及对应计数。
在 Laravel 开发中,常需对数据进行聚合统计并施加分组后过滤条件(即 SQL 中的 HAVING 子句),例如:统计每天的预约数量,并只显示预约数 ≥
某一动态阈值(如 $max = 3)的日期。原生 SQL 可直接写为:
SELECT COUNT(date) AS numberofreservations, date FROM reservations GROUP BY date HAVING numberofreservations >= 3;
Laravel 提供了两种优雅方式实现该逻辑:Eloquent 模型查询 和 Query Builder。
$max = (int) $request->input('min_count', 2); // 从请求或数据库动态获取,注意类型安全
$reservationsByDate = Reservation::selectRaw('COUNT(date) as numberofreservations, date')
->groupBy('date')
->havingRaw('COUNT(date) >= ?', [$max]) // ✅ 推荐:使用参数绑定防 SQL 注入
->orderBy('date')
->get();? 注意:havingRaw() 中使用 ? 占位符配合数组参数(如 [$max])比字符串拼接更安全,避免 SQL 注入风险。
use Illuminate\Support\Facades\DB;
$max = config('app.min_reservation_threshold', 1); // 也可从配置/数据库读取
$reservationsByDate = DB::table('reservations')
->selectRaw('COUNT(date) as numberofreservations, date')
->groupBy('date')
->havingRaw('COUNT(date) >= ?', [$max])
->orderBy('date')
->get();开发阶段可快速验证查询是否符合预期:
// 输出 SQL 并终止执行(推荐用于调试)
DB::table('reservations')
->selectRaw('COUNT(date) as numberofreservations, date')
->groupBy('date')
->havingRaw('COUNT(date) >= ?', [$max])
->dd(); // ← 输出完整 SQL 及绑定参数,便于排查->selectRaw('COUNT(*) as numberofreservations, DATE(date) as date')
->groupBy('DATE(date)')
->havingRaw('COUNT(*) >= ?', [$max])public function dailyStats(Request $request)
{
$max = (int) $request->query('min', 2);
$stats = Reservation::selectRaw('COUNT(*) as count, DATE(date) as day')
->groupBy('DATE(date)')
->havingRaw('COUNT(*) >= ?', [$max])
->orderBy('day')
->get();
return response()->json($stats);
}返回结果示例:
[
{"count": 5, "day": "2025-05-01"},
{"count": 3, "day": "2025-05-03"}
]掌握 groupBy() 与 havingRaw() 的组合用法,能高效处理 Laravel 中各类分组统计需求,兼顾可读性、安全性与数据库兼容性。