vendredi 5 avril 2019

calculate column of related model while in pagination

I have a model named Invoice which is has relation of hasMany to InvoiceItems. in InvoiceItems there is a field/column named total. how do I calculate that field when dealing with pagination? here is the code

$periode = $months_translate[date('n') - 1].'-'.date('Y');

$invoices = Invoice::where('billing_period', $periode)
->orderBy('number')->paginate($per_page);

$total_amount = 0; // this is what i am trying to figure out.
foreach($invoices as $invoice){
    foreach($invoice->items as $item){
        $total_amount += $item->sum('total');
    }
}

$total_amount is calcuating all records, including outside current billing_period scoop, so simply it's give wrong result.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire