Dhiemas Ganisha
Dhiemas Ganisha

Reputation: 223

Using sum in eloquent laravel when have quantity and price

I have problem with my projects e-commerce in,in this problem i have 2 tables.

Table Products

ID     | Name_products   | Price
P1     | Product A       | 2000
P2     | Product B       | 5000
P3     | Product C       | 7500

Table User Carts

ID     | User_id    | Product_id  | Quantity
C1     | User1      | P1          | 2
C2     | User1      | P2          | 1

I have using this query eloquent :

$totalPricec = MyCart::where('user_id', Auth::user()->id)
               ->select('products.nama_produk', 'products.id as product_id','products.price''my_carts.quantity','my_carts.id as id')
               ->join('products', 'products.id', '=', 'my_carts.product_id')
               ->sum('price');

but i got price is 7000 (product A = 2000 + product B = 5000)

should be 9000 (product A = 2000 * 2 + product B = 5000 * 1)

how i can get the total price actually?

Upvotes: 2

Views: 4219

Answers (1)

Dhiemas Ganisha
Dhiemas Ganisha

Reputation: 223

I using this query

$totalPricec = MyCart::where('user_id', Auth::user()->id)
           ->select('products.nama_produk', 'products.id as product_id','products.price''my_carts.quantity','my_carts.id as id')
           ->join('products', 'products.id', '=', 'my_carts.product_id')
           ->sum(DB::raw('products.price * my_carts.quantity'));

and thats work :)

thank you for user @user3532758

Upvotes: 4

Related Questions