
本文讲解如何在 Laravel 中正确构建查询条件,使记录满足“大于等于开始时间、且仅当结束时间存在时小于等于结束时间”的逻辑,避免因 end_at 为 NULL 导致查询失效。
本文讲解如何在 laravel 中正确构建查询条件,使记录满足“大于等于开始时间、且仅当结束时间存在时小于等于结束时间”的逻辑,避免因 `end_at` 为 null 导致查询失效。
在实际业务中,常遇到类似 start_at(必填)与 end_at(可空)共存的时间范围字段。例如活动、价格策略或权限有效期等场景:若 end_at 为空,表示长期有效;若非空,则需严格落在 [start_at, end_at] 闭区间内。此时直接使用 whereBetween() 或固定双条件 where(...)->where(...) 均不可行——前者要求两端非空,后者会因 NULL >= $effectiveDate 恒为 false 而漏掉无截止日期的有效记录。
正确的做法是使用 条件化查询(Conditional Clauses),结合 whereNull() 与 whereNotNull() 分支逻辑:
$effectiveDate = '2022-04-06 23:34:00';
GroupExtras::query()
->select('group_extras.*')
->join('groups', 'group_extras.group_id', '=', 'groups.id')
->where('group_extras.start_at', '<=', $effectiveDate)
->where(function ($query) use ($effectiveDate) {
// 分支一:end_at 为 NULL → 视为无限期,无需额外限制
$query->whereNull('group_extras.end_at')
// 分支二:end_at 非 NULL → 必须 >= effectiveDate
->orWhere(function ($sub) use ($effectiveDate) {
$sub->whereNotNull('group_extras.end_at')
->where('group_extras.end_at', '>=', $effectiveDate);
});
})
->orderBy('group_extras.value')
->first();✅ 关键点说明:
- 主条件 start_at <= $effectiveDate 确保所有候选记录已生效;
- 匿名闭包内使用 whereNull() 和 orWhere(...) 实现“或”逻辑:只要满足「无结束时间」或「有结束时间且未过期」任一条件即保留;
- 避免在 where() 中直接比较 NULL(如 end_at >= ?),因为 SQL 中 NULL >= value 返回 UNKNOWN,导致该行被排除。
⚠️ 注意事项:
- 不要误用 whereBetween('column', [$start, $end]):它底层生成 column BETWEEN $start AND $end,当 $end 为 null 时语句非法或恒假;
- 若需兼容 MySQL 5.7+ 严格模式,建议显式使用 DB::raw() 或 Carbon 格式化时间,确保 $effectiveDate 是标准 Y-m-d H:i:s 字符串;
- 对于大数据量表,应在 start_at 和 end_at 上建立联合索引(如 INDEX(start_at, end_at))以提升查询性能。
此方案兼顾语义清晰性与数据库兼容性,是 Laravel 中处理“半开放时间区间”的推荐实践。


















