Laravel вывод данных из бд за год

Рейтинг: 0Ответов: 1Опубликовано: 20.05.2023

Нужно вывести данные за весь год помесячно, посчитав у двух столбцов общее количество, при том у столбца invoice_status посчитать только данные с "send" и "end".

ModelData::selectRaw('monthname(date) as month date, count(price) as price, count(invoice_status) as invoice')
 ->whereIn('invoice_status',['send', 'end'])
                            ->groupBy('month')
                            ->orderByRaw('min(date) asc')
                            ->get();

Выдаёт так:

{month: "April", price: 2, invoice: 2}
{month: "May", price: 13, invoice: 13}

Должно быть так:

{month: "April", price: 2, invoice: 1}
{month: "May", price: 13, invoice: 4}

Формат базы следующий:

id |     date      |price | invoice
 1    2022-05-30     150      send
 2    2022-04-20     250      null
 3    2022-01-20     180      null
 4    2022-02-20     80       end

Ответы

▲ 0

Сам решил, может кому будет нужно:

ModelData::select($columns)
->whereBetween('date',[
     Carbon::now()->subYear(0)->startOfYear(),
     Carbon::now()->subYear(0)->endOfYear()
     ]
   )
->whereIn('invoice_status',['send', 'end'])
->orderBy('date')
->get()
->groupBy(function($data) {
      return Carbon::parse($data->date)->format('F');
})
->map(function($entries) {
     return $entries->count();
})
);