【问题标题】:How to calculate total price of multiple items in cart in Laravel?如何计算 Laravel 购物车中多个商品的总价格?
【发布时间】:2021-04-17 10:23:31
【问题描述】:

我有一个购物车表,其中列是---->“id”、“user_id”、“product_id”、“quantity”。看图

这里是产品表

当用户将商品添加到购物车时,我想获取用户添加到购物车中的产品总价。该怎么做?

这是购物车模型

这里是产品型号

【问题讨论】:

  • 你的模型中定义了关系吗?
  • 是的,我在模型中定义了它
  • 有几种方法可以做到这一点。我将发布一个选项作为答案。
  • 请发表您的答案。

标签: php mysql laravel eloquent eloquent-relationship


【解决方案1】:

一个选项:

您可以在用户模型中编辑现有关系或为购物车创建新关系以加入产品表并进行计算以获得总价。

//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')
                     );
}

当您调用 User::with('cartsWithProductPrice')->find(1); 时,它应该为您提供与名为 price 的字段的购物车关系以及总价。

希望这将为您指明正确的方向。

【讨论】:

    猜你喜欢
    • 2019-12-09
    • 2023-01-12
    • 1970-01-01
    • 1970-01-01
    • 2021-09-07
    • 2021-06-28
    • 1970-01-01
    • 2021-08-10
    • 2019-12-30
    相关资源
    最近更新 更多