Home > Enterprise >  how to GROUP BY data in multi relational table (laravel eloquent)
how to GROUP BY data in multi relational table (laravel eloquent)

Time:09-21

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();

CodePudding user response:

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/>";
}

CodePudding user response:

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.

  • Related