dimanche 29 avril 2018

Laravel Sum Eloquent sum of multiple multiplications from two different tables

Currently, in my Laravel project controller, I am using one query

public function cartreview(Request $request,$sp_id, $service_id,$cart_id)
    {
    $total = DB::table('pricings')
    ->join('carts', 'carts.sp_id', '=', 'pricings.sp_id')
    ->select(DB::raw('sum(pricings.shirt*carts.quantity_shirt ) AS total'))                      
    ->where('pricings.sp_id', '=', $sp_id)
    ->where('carts.id', '=' , $cart_id)
    ->first();
    }

In above query, I am using two database tables as pricings and carts where I am calculating total bill price of shirt item by getting a price from pricing table and quantity from carts table.

Now I also want to add another item with a shirt like a pant, tie, etc. How do I pass more multiplication to the sum?

Please help me with the syntax. Can I do something like this

    $total = DB::table('pricings')
        ->join('carts', 'carts.sp_id', '=', 'pricings.sp_id')
        ->select(DB::raw('sum(pricings.shirt*carts.quantity_shirt ,
                             pricings.pant*carts.quantity_pant , 
                             pricings.tie*carts.quantity_tie) AS total'))                      
        ->where('pricings.sp_id', '=', $sp_id)
        ->where('carts.id', '=' , $cart_id)
        ->first();

OR even if I calculate total separately for each item How do I add it?

$total_shirt = DB::table('pricings')
    ->join('carts', 'carts.sp_id', '=', 'pricings.sp_id')
    ->select(DB::raw('sum(pricings.shirt*carts.quantity_shirt ) AS total_shirt'))                      
    ->where('pricings.sp_id', '=', $sp_id)
    ->where('carts.id', '=' , $cart_id)
    ->first();

   $total_pant = DB::table('pricings')
    ->join('carts', 'carts.sp_id', '=', 'pricings.sp_id')
    ->select(DB::raw('sum(pricings.pant*carts.quantity_pant ) AS total_pant'))                      
    ->where('pricings.sp_id', '=', $sp_id)
    ->where('carts.id', '=' , $cart_id)
    ->first();

   $total_tie = DB::table('pricings')
    ->join('carts', 'carts.sp_id', '=', 'pricings.sp_id')
    ->select(DB::raw('sum(pricings.tie*carts.quantity_tie ) AS total_tie'))                      
    ->where('pricings.sp_id', '=', $sp_id)
    ->where('carts.id', '=' , $cart_id)
    ->first();

$total = $total_shirt + $total_pant + $total_tie; ?

To display value in view.blade.php I use something like

Thanks in advance.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire