skip to Main Content

I have joined 2 databases, what i want is to get the total value/sum of these 2 multiplied column:

Example on the database:

Price Quantity
100 1
110 2
120 3

in my query in laravel- i got the total, 100, 220, 360, i want the sum of all these, total that is equals to, 680, how can i achieve the 680 total?

    $jointwo = DB::table('invoices')
                ->select('invoices.id', 'invoices.user', 'invoices.company', 'invoices.invoice_month', 'invoices.created','invoice_details.invoice_id', DB::raw('invoice_details.quantity * invoice_details.unit_price as total'))->join('invoice_details', 'invoice_details.invoice_id', '=', 'invoices.id')->get();


     dd($jointwo);

I got the total, 100, 220, 360, i want the sum of all these, total that is equals to, 680, how can i achieve the 680 total?

2

Answers


  1. you can use the sum function.

    $jointwo = DB::table('invoices')
        ->select('invoices.id', 'invoices.user', 'invoices.company', 'invoices.invoice_month', 'invoices.created', 'invoice_details.invoice_id', DB::raw('invoice_details.quantity * invoice_details.unit_price as total'))
        ->join('invoice_details', 'invoice_details.invoice_id', '=', 'invoices.id')
        ->get();
    
    // total sum of the 'total' column
    $totalSum = $jointwo->sum('total');
    
    dd($totalSum);
    
    Login or Signup to reply.
  2. first, group by invoices.id ->groupBy('invoices.id') and then get the total amount.

    $jointwo = DB::table('invoices')
        ->select('invoices.id', 'invoices.user', 'invoices.company', 'invoices.invoice_month', 'invoices.created')
        ->selectRaw('SUM(invoice_details.quantity * invoice_details.unit_price) as total')
        ->join('invoice_details', 'invoice_details.invoice_id', '=', 'invoices.id')
        ->groupBy('invoices.id')
        ->get();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search