1

I'm stuck in a problem that how to GROUP BY data in multi relational table. Here is my code:

$invoices = Invoice::select('id', 'date', 'type')
            ->with('invoice_items:invoice_id,item_id,amount', 'invoice_items.item_title:id,name')
            ->latest('id')
            ->get();
mahbub
  • 103
  • 1
  • 3
  • 13

2 Answers2

0

I solved the problem this way --

$invoices = Invoice::select('id', 'date', 'type')
              ->with('invoice_items:invoice_id,item_id,amount', 'invoice_items.item_title:id,name')
              ->latest('id')
              ->get();


foreach($invoices as $invoice)
{
   echo date('d.M.Y', strtotime($invoice->date)) . "--- <br/> ";

   $items = $invoice->invoice_items->groupBy('item_id');

   foreach($items as $item)
   {
      echo $item[0]['item_title']['name'] . ' - ' . $item->sum('amount') . "<br/>";
   }

   echo "<br/><br/>";
}
mahbub
  • 103
  • 1
  • 3
  • 13
0

Looping in the controller is not good practice.

It's better to use the with method with the callback function :

Model::with(['relation',function($relationQuery){
       $relationQuery->groupBy('relation_field');
   }]);

I hope it helps.

Royal_MGH
  • 766
  • 4
  • 8