tp5(thinkPHP5框架)時間查詢操作實例分析

這篇文章主要介紹了tp5(thinkPHP5框架)時間查詢操作,結合實例形式分析了thinkPHP5框架數據庫中日期時間查詢相關操作技巧,需要的朋友可以參考下

本文實例講述了tp5(thinkPHP5框架)時間查詢操作。分享給大家供大家參考,具體如下:

在項目中 可能會遇到 跨月份進行查詢

比如在 當輸入201809 會獲取當月的開始時間$start_month 和 結束時間 $end_month

會查詢2018年9月份的數據 但是當其中的一個數據是在201809到201810 ,數據庫的字段是 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','2016-1-1');
// 小於某個時間
where('create_time','<= time','2016-1-1');
// 時間區間查詢
where('create_time','between time',['2015-1-1','2016-1-1']);

使用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();

參考地址:https://www.kancloud.cn/he_he/thinkphp5

更多關於thinkPHP相關內容感興趣的讀者可查看本站專題:《ThinkPHP入門教程》、《thinkPHP模板操作技巧總結》、《ThinkPHP常用方法總結》、《codeigniter入門教程》、《CI(CodeIgniter)框架進階教程》、《Zend FrameWork框架入門教程》及《PHP模板技術總結》。

希望本文所述對大家基於ThinkPHP框架的PHP程序設計有所幫助。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章