知识笔记(九十)———ThinkPHP5中时间查询的方法

时间比较

使用where方法

where方法支持时间比较,例如:

复制代码
// 大于某个时间
where('create_time','> time','2016-1-1');
// 小于某个时间
where('create_time','<= time','2016-1-1');
// 时间区间查询
where('create_time','between time',['2015-1-1','2016-1-1']);

第三个参数可以传入任何有效的时间表达式,会自动识别你的时间字段类型,支持的时间类型包括timestampsdatetimedateint

使用whereTime方法

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();
相关推荐
马克学长2 分钟前
SSM医院门诊管理系统u4pw5(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面
数据库·ssm 框架·javaweb 开发·门诊管理
TDengine (老段)3 分钟前
使用安装包快速体验 TDengine TSDB
大数据·数据库·物联网·时序数据库·tdengine·涛思数据
闻哥42 分钟前
Redis 避坑指南:从命令到主从的全链路踩坑实录
java·数据库·redis·缓存·面试·springboot
junnhwan1 小时前
【计算机网络-CS168-textbook阅读笔记】传输层原理与TCP设计
笔记·计算机网络·tcp·cs168
建群新人小猿2 小时前
陀螺匠企业助手—个人简历
android·大数据·开发语言·前端·数据库
wdfk_prog2 小时前
[Linux]学习笔记系列 -- [drivers][base]platform
linux·笔记·学习
小毅&Nora2 小时前
【后端】【Redis】② Redis事务管理全解:从“购物车结算“到“银行转账“,一文彻底掌握事务机制
数据库·redis·事务
u0109272713 小时前
持续集成/持续部署(CI/CD) for Python
jvm·数据库·python
cs.shunzhang3 小时前
[特殊字符]【实战笔记】解锁 oh-my-opencode 隐藏技巧:用 ulw 和 ralph-loop 压榨 AI 极限
笔记
玄同7654 小时前
深入理解 SQLAlchemy 的 relationship:让 ORM 关联像 Python 对象一样简单
人工智能·python·sql·conda·fastapi·pip·sqlalchemy