laravel按天、按小时,查询数据的实例

吾爱主题 阅读:112 2021-08-27 15:24:00 评论:0

使用laravel做后台数据统计的时候,需要查询每天的注册量之类的数据

这时候如果直接用created_at分组,是不好用的。

1、所以本文解决这个查询应该怎么写。

2、并且推荐一个时间选择插件,因为统计中一定会用到,本周数据、本月、本季度、上个月。。。。

按天分组数据:

?
1 2 3 4 5 6 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();

如果想按小时分组所有查询出来的数据:

?
1 2 3 4 5 6 7 8 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()

分享一个时间选择插件

这是官网地址

我把我改好的代码附上:

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 $( function () { /*设置开始结束时间*/   var start = moment().subtract(30, 'days' );   var end = moment().subtract(-1, 'day' );   var datas = {}; /*选择之后,将时间重新赋值input*/   function cb(start, end ) {    $( '#reportrange span' ).html(start.format( 'YYYY/MM/DD' ) + ' - ' + end .format( 'YYYY/MM/DD' ));   }   $( '#reportrange' ).daterangepicker({   startDate: start,   endDate: end ,   /*本地化数据*/   locale: {    "format" : "YYYY/MM/DD" ,    "separator" : " - " ,    "applyLabel" : "应用" ,    "cancelLabel" : "关闭" ,    "fromLabel" : "From" ,    "toLabel" : "至" ,    "customRangeLabel" : "自定义" ,    "weekLabel" : "W" ,    "daysOfWeek" : [ "Su" , "Mo" , "Tu" , "We" , "Th" , "Fr" , "Sa"    ],    "monthNames" : [ "一月" , "二月" , "三月" , "四月" , "五月" , "六月" , "七月" , "八月" , "九月" , "十月" , "十一月" , "十二月"    ],    "firstDay" : 1   },   ranges: {    '今天' : [moment(), moment().subtract(-1, 'days' )],    '昨天' : [moment().subtract(1, 'days' ), moment()],    '前7天' : [moment().subtract(7, 'days' ), moment()],    '前30天' : [moment().subtract(30, 'days' ), moment()],    '本月' : [moment().startOf( 'month' ), moment().endOf( 'month' ).subtract(-1, 'day' )],    '上月' : [moment().subtract(1, 'month' ).startOf( 'month' ), moment().subtract(1, 'month' ).endOf( 'month' ).subtract(-1, 'day' )],    '所有' : [moment( "2017-09-25" ), moment().subtract(-1, 'days' )]   } }, cb);     cb(start, end ); });

超级好用,结合echart

在用echart的map时候,因为地图权限没有,所以要加载百度地图。这个坑另开帖子记录吧。

以上这篇laravel按天、按小时,查询数据的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/yushengphper/article/details/78498368

可以去百度分享获取分享代码输入这里。
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

【腾讯云】云服务器产品特惠热卖中
搜索
标签列表
    关注我们

    了解等多精彩内容