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
中看到:
转为UTCDateTime后就可以愉快的使用whereBetween进行查询了。
另外,如果使用mongodb,可以在存入数据的时候,附带存入时间戳,后续进行查询也更方便!
本作品采用《CC 协议》,转载必须注明作者和本文链接
推荐文章: