Laravel MongoDB 时间区间查询的问题

laravel下使用MongoDB扩展,有默认时间,两个字段为created_at和updated_at,时间格式为:

"updated_at" => UTCDateTime {#419 ▼
   +"milliseconds": "1560842012000"
 }

UTCDateTime 的格式为对象,有两种查询方式,一种为:

 $today = Carbon::today();
 $tomorrow = Carbon::today()->addDays(1);
 $res = MongoLog::where("created_at",">",$today)->where("created_at","<",$tomorrow)->get();

此处的 $today和$tomorrow为datatime对象,但是并不能使用wherebetween查询,带来诸多不便。wherebetween查询条件为数组,数组里面的元素为字符串或者是整型。

另一种为:

把datetime转为UTCDateTime格式进行查询:

详情见:https://blog.csdn.net/u012560213/article/d...

事例里使用了time()函数,为当前时间的时间戳,不能满足要求,所以改为strtotime()

代码:

$t1 = Carbon::today()->toDateTimeString();
$t2 = Carbon::today()->subDays(7)->toDateTimeString();

//转为时间戳再转为UTCDateTime
$a1 = new UTCDateTime(strtotime($t1)*1000);
$a2 = new UTCDateTime(strtotime($t2)*1000);
$res = AccessLog::whereBetween("created_at",[$a2,$a1])->get();

注意:UTCDateTime格式为毫秒,可以在

vendor\jenssegers\mongodb\src\Jenssegers\Mongodb\Auth的DatabaseTokenRepository.php

中看到:

laravel mongodb时间区间查询的问题

转为UTCDateTime后就可以愉快的使用whereBetween进行查询了。

另外,如果使用mongodb,可以在存入数据的时候,附带存入时间戳,后续进行查询也更方便!

本作品采用《CC 协议》,转载必须注明作者和本文链接
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!