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 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 qgcomp混合物线性模型分析的代码出现错误:Model aliasing occurred
  • ¥100 已有python代码,要求做成可执行程序,程序设计内容不多
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助
  • ¥15 STM32控制MAX7219问题求解答
  • ¥20 在本地部署CHATRWKV时遇到了AttributeError: 'str' object has no attribute 'requires_grad'