Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

php - How to calculate total price of multiple items in cart in Laravel?

I have a carts table where column is----> "id", "user_id", "product_id", "quantity". See the image carts table image

here is ther products table products table

When a user add item into cart ,I want to get total price of products which is added into cart by the user. How to do that?

Here is the cart model cart model

Here is the product model product model


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

One option:

You can edit the existing relationship or create a new relationship for Cart in the User model to join the products table and do a calculation to get the total price.

//User model
public function cartsWithProductPrice(){
 return $this->hasMany(Cart::class)
             ->join('products', 'carts.product_id', 'products.id')
             ->select('carts.*', 
                      DB::raw('carts.quantity * products.price as price')
                     );
}

And when you call for example User::with('cartsWithProductPrice')->find(1); it should give you the cart relationship with a field named price with total price.

Hope that this will point you in the right direction.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...