ThinkPHP5时间查询基础
本示例详细解析ThinkPHP5框架的时间查询机制,供读者参考借鉴。
实际开发中常需处理跨越月份的数据检索需求。
例如输入202609时,系统获取当月起始时间$start_month与结束时间$end_month。
此时需查询2026年9月数据,若某条记录的时间段横跨202609至202610,且数据库字段为start_time与end_time。
针对此类情况,
Db::name("表名")->where('start_time','<= time',$end_month)
->where('end_time','> time',$start_month)
->select();
涉及时间比较逻辑。
可调用where方法。
where方法支持时间类型比较,具体用法如下:
// 大于某个时间
where('create_time','> time','2026-1-1');
// 小于某个时间
where('create_time','<= time','2016-1-1');
// 时间区间查询
where('create_time','between time',['2015-1-1','2016-1-1']);
此外,whereTime方法提供日期和时间字段的快捷查询接口。
其示例代码如下:
// 大于某个时间
Db::table('think_user')->whereTime('birthday', '>=', '1970-10-1')->select();
// 小于某个时间
Db::table('think_user')->whereTime('birthday', '<', '2000-10-1')->select();
// 时间区间查询
Db::table('think_user')->whereTime('birthday', 'between', ['1970-10-1', '2000-10-1'])->select();
// 不在某个时间区间
Db::table('think_user')->whereTime('birthday', 'not between', ['1970-10-1', '2000-10-1'])->select();
框架还内置更便捷的时间表达式查询功能。
例如可实现以下查询:
// 获取今天的博客
Db::table('think_blog') ->whereTime('create_time', 'today')->select();
// 获取昨天的博客
Db::table('think_blog')->whereTime('create_time', 'yesterday')->select();
// 获取本周的博客
Db::table('think_blog')->whereTime('create_time', 'week')->select();
// 获取上周的博客
Db::table('think_blog')->whereTime('create_time', 'last week')->select();
// 获取本月的博客
Db::table('think_blog')->whereTime('create_time', 'month')->select();
// 获取上月的博客
Db::table('think_blog')->whereTime('create_time', 'last month')->select();
// 获取今年的博客
Db::table('think_blog')->whereTime('create_time', 'year')->select();
// 获取去年的博客
Db::table('think_blog')->whereTime('create_time', 'last year')->select();
若需查询当天、本周、本月或今年数据,可使用简化语法:
// 获取今天的博客
Db::table('think_blog')->whereTime('create_time', 'd')->select();
// 获取本周的博客
Db::table('think_blog')->whereTime('create_time', 'w')->select();
// 获取本月的博客
Db::table('think_blog')->whereTime('create_time', 'm')->select();
// 获取今年的博客
Db::table('think_blog')->whereTime('create_time', 'y') ->select();
V5.0.5+版本开始,还可以使用下面的方式进行时间查询
// 查询两个小时内的博客
Db::table('think_blog')->whereTime('create_time','-2 hours')->select();
官方文档参考地址:https://www.kancloud.cn/he_he/thinkphp5
期望上述内容对基于ThinkPHP框架的PHP编程实践有所助益。