You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Laravel中使用query()函数筛选两个日期之间的数据

结论

可以实现,你当前的默认遍历逻辑是把所有请求参数都作为等于条件拼接,需要针对fromdate和todate两个特殊参数做单独的区间查询适配即可,参考修改方案如下:


方案1:保留原有通用查询逻辑,单独处理日期参数

$my_query = Deathregister::query();
foreach ($request->query() as $key => $value) {
    if ($key === 'fromdate') {
        // 替换为你实际存储日期的字段名,比如created_at、death_date等
        $my_query->where('日期字段名', '>=', $value);
    } elseif ($key === 'todate') {
        $my_query->where('日期字段名', '<=', $value);
    } else {
        // 其余参数保持原有等于查询逻辑
        $my_query->where($key, $value);
    }
}
$result = $my_query->get();

方案2:优先处理日期区间,逻辑更清晰

$my_query = Deathregister::query();
// 两个日期参数都存在时走区间查询
if ($request->has(['fromdate', 'todate'])) {
    $my_query->whereBetween('日期字段名', [
        $request->input('fromdate'),
        $request->input('todate')
    ]);
}
// 排除日期参数后,其余参数走原有等于查询
foreach ($request->except(['fromdate', 'todate']) as $key => $value) {
    $my_query->where($key, $value);
}
$result = $my_query->get();

注意事项

  • 请将代码中的日期字段名替换为你Deathregister模型对应数据表中实际存储日期的字段
  • 如果你的日期字段是datetime/timestamp类型,想要包含todate当天的全部数据,可以把todate的条件改为whereDate('日期字段名', '<=', $value),或者给todate拼接 23:59:59后缀
  • 建议增加参数校验逻辑,提前验证fromdate、todate为合法日期格式,避免非法参数导致查询异常

内容的提问来源于stack exchange,提问作者Sushant Malvadakar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 07:24:03