時間比較
使用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']);
第三個參數可以傳入任何有效的時間表達式,會自動識別你的時間字段類型,支持的時間類型包括timestamps
、datetime
、date
和int
。
使用whereTime
方法
whereTime
方法提供了日期和時間字段的快捷查詢,示例如下:
// 大於某個時間 db('user') ->whereTime('birthday', '>=', '1970-10-1') ->select(); // 小於某個時間 db('user') ->whereTime('birthday', '<', '2000-10-1') ->select(); // 時間區間查詢 db('user') ->whereTime('birthday', 'between', ['1970-10-1', '2000-10-1']) ->select(); // 不在某個時間區間 db('user') ->whereTime('birthday', 'not between', ['1970-10-1', '2000-10-1']) ->select();
時間表達式
還提供了更方便的時間表達式查詢,例如:
// 獲取今天的博客 db('blog') ->whereTime('create_time', 'today') ->select(); // 獲取昨天的博客 db('blog') ->whereTime('create_time', 'yesterday') ->select(); // 獲取本周的博客 db('blog') ->whereTime('create_time', 'week') ->select(); // 獲取上周的博客 db('blog') ->whereTime('create_time', 'last week') ->select(); // 獲取本月的博客 db('blog') ->whereTime('create_time', 'month') ->select(); // 獲取上月的博客 db('blog') ->whereTime('create_time', 'last month') ->select(); // 獲取今年的博客 db('blog') ->whereTime('create_time', 'year') ->select(); // 獲取去年的博客 db('blog') ->whereTime('create_time', 'last year') ->select();
如果查詢當天、本周、本月和今年的時間,還可以簡化為:
// 獲取今天的博客 db('blog') ->whereTime('create_time', 'd') ->select(); // 獲取本周的博客 db('blog') ->whereTime('create_time', 'w') ->select(); // 獲取本月的博客 db('blog') ->whereTime('create_time', 'm') ->select(); // 獲取今年的博客 db('blog') ->whereTime('create_time', 'y') ->select();