dongni1892 2019-04-27 17:04
浏览 130
已采纳

如何计算和按月分组,月份为零

I am trying to set up a small statistical module. I am looking for an array containing for each month the number of events of my 'evenement' table. With the query below I get the results but only if there is a result in the month. IF there is none, it does not appear. My request:

$data = DB::table("evenements")
        ->select(DB::raw('EXTRACT(MONTH FROM datedevenement) AS month, COUNT(id) as id'),
         DB::raw('ifnull(count(id),0) as id')
        )
         ->where('typeevenement_id', '1')
        ->whereYear('datedevenement', Carbon::now()->year)
        ->orderBy('datedevenement')

        ->groupBy(DB::raw('month'))
        ->get();



    return $data;

My evenement table :

id | datedevenement | typeevenement_id

I understand that my request can not invent months that do not exist. I wonder if carbon or laravel does not have something to list by month or year in a continuous way.

Result must be an array or collection with monthORyears->count(evenement)

  • 写回答

3条回答 默认 最新

  • duanqiao1926 2019-04-30 13:57
    关注

    Thanks you. With this 2 answers and a small serach i arrived to this solution (i have add somathing for order with current month for start point) :

    $monthly_uploaded_product = Evenement::select(DB::raw('COUNT(id) as total, EXTRACT(MONTH FROM datedevenement) AS month')
        )
            ->where('typeevenement_id', '1')
            ->wheredate('datedevenement', '>=', Carbon::now()->lastOfMonth()->subyears(1))
           /// ->whereYear('datedevenement', Carbon::now()->year)
           ->groupBy(DB::raw('month'))
    
            ->get();
    
        $mois  = ["janvier", "fevrier", "mars", "avril", "mai", "juin", "juillet", "aout", "septembre", "octobre", "novembre", "decembre"];
    
        foreach ($mois as $mois99) {
            $arriveeparmoisrefuge[]= array(
                'mois' => $mois99,
                'total' => '0'
            );
    
        }
            foreach ($monthly_uploaded_product as $key) {
                    $arriveeparmoisrefuge[$key->month - 1]['total'] = $key->total;//update each month with the total value
            }
        $sorted = collect($arriveeparmoisrefuge)->sortBy(function ($count, $month) {
            $currentMonth = (int) \Carbon\Carbon::now()->month;
    
            return ($month + (13 - $currentMonth - 1)) % 12;
        });
    
        return  $sorted;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题