按时间查询可以做很多统计工作。比如统计今日页面日活,统计本月注册量,统计年度更新等等。Laravel由于使用了timestamp统一部署,想要直接用created_at分组时间,就比较困难。
解决方案如下:
按天分组数据:
Event::where('created_at','>',Carbon::parse($request->start_date))
->where('created_at','<',Carbon::parse($request->end_date))
//两个where限制开始结束时间
->groupBy('date')
->get([DB::raw('DATE(created_at) as date'),DB::raw('COUNT(*) as value')])
->toArray();
如果想按小时分组所有查询出来的数据:
php">Event::where('created_at','>',Carbon::parse('2017-01-01'))
->where('created_at','<',Carbon::parse('2017-11-09'))
->groupBy('day')
->get([
//通过date_format()来格式化created_at字段
DB::raw('DATE_FORMAT(created_at,\'%H\') as day'),
DB::raw('COUNT(*) as value')])
->toArray()
这里需要引入Carbon类。不熟悉Carbon的朋友们可以接着往下看。
Carbon类
Carbon是DateTime的简单PHP API扩展,Laravel环境中已默认配置。该类可以满足绝大部分的时间处理需要。废话少说,看实例:
php"> use Carbon\Carbon; //引入Carbon类
printf("Right now is %s", Carbon::now()->toDateTimeString()); //当前时间
printf("Right now in Vancouver is %s", Carbon::now('America/Vancouver')); //implicit __toString() //时区计算
$tomorrow = Carbon::now()->addDay(); //日计算
$lastWeek = Carbon::now()->subWeek(); //周计算
$nextSummerOlympics = Carbon::createFromDate(2016)->addYears(4); //年计算
$officialDate = Carbon::now()->toRfc2822String(); //标准时间
$howOldAmI = Carbon::createFromDate(1975, 5, 21)->age; //计算年龄
$noonTodayLondonTime = Carbon::createFromTime(12, 0, 0, 'Europe/London'); //产生制定时间戳
$internetWillBlowUpOn = Carbon::create(2038, 01, 19, 3, 14, 7, 'GMT');
// Don't really want this to happen so mock now
Carbon::setTestNow(Carbon::createFromDate(2000, 1, 1));
// comparisons are always done in UTC
if (Carbon::now()->gte($internetWillBlowUpOn)) {
die();
}
// Phew! Return to normal behaviour
Carbon::setTestNow();
if (Carbon::now()->isWeekend()) {
echo 'Party!';
}
echo Carbon::now()->subMinutes(2)->diffForHumans(); // '2 minutes ago'
// ... but also does 'from now', 'after' and 'before'
// rolling up to seconds, minutes, hours, days, months, years
$daysSinceEpoch = Carbon::createFromTimestamp(0)->diffInDays();
看得头晕没关系,详细说明可以参考下一页Carbon具体使用方法合集。