如何简化 Laravel 按年搜索日期并按月分组的查询

How do I simplify Laravel query for date searching by year and grouping by month

有没有办法简化?我为整个日期、月份和年份选择了 date_billing 列三次。有没有办法做类似 ->having('YEAR(date_billing)', '=', $this->year); 和月份相同的事情?我的工作有效,但重复了很多,我相信有更好的方法。下面是

->addSelect([
    'date_billing' => Invoice::select(DB::raw('date_billing'))
     ->whereColumn("id", "=", "invoice_line_item.invoice_id"),
       
     'month' => Invoice::select(DB::raw('MONTH(date_billing) month'))
      ->whereColumn("id", "=", "invoice_line_item.invoice_id"),
    
     'year' => Invoice::select(DB::raw('YEAR(date_billing) year'))
      ->whereColumn("id", "=", "invoice_line_item.invoice_id")
])
->having('year' ,'=', $this->year)
->groupBy('month')
->get();

编辑:

我通过添加 ->whereYear() 修复了 'year' 允许我从 addSelect 数组中取出 'year',但我仍然必须有月份。

->addSelect([
   'date_billing' => Invoice::select(DB::raw('date_billing'))
   ->whereColumn("id", "=", "invoice_line_item.invoice_id"),
   ->whereYear("date_billing", $this->year),

    'month' => Invoice::select(DB::raw('MONTH(date_billing) month'))
    ->whereColumn("id", "=", "invoice_line_item.invoice_id"),
])

有意思,我以前没用过addSelectwhereColumn

这是未经测试的猜测,如果查询构建器还有其他部分,那么查看这些部分会有所帮助。

您在任何地方使用 joinleftJoin 吗?

->addSelect(DB::raw('date_billing, YEAR(date_billing) year'))
->whereColumn('id', 'invoice_line_item.invoice_id')
->having('year', '=', $this->year)
->groupByRaw('MONTH(date_billing)')
->get();