【问题标题】:Laravel Cart Sum based on input from 2 different tables基于来自 2 个不同表的输入的 Laravel 购物车总和
【发布时间】:2020-07-25 17:34:44
【问题描述】:

我有 2 个桌子袋(购物车)和产品。我正在保存用户在坏表中添加的数量和产品表中的 sale_price。我需要为每件商品获取 bag.quantity * products.sale_price 的总和。我正在使用查询生成器来获取总和。我怎样才能得到它

我可以使用 join 来获取所有属性的列表

$items = DB::table('bag')->where('bag.user_id' , $user_id)->where('bag.order_id', 0)->join('products','products.id','=','bag.product_id')->get();

api链接:

https://apptest.factory2homes.com/api/get-bag-products/3

我需要将每个唯一 product_id 的数量和 sale_price 相乘,然后求总和

【问题讨论】:

  • 你想得到什么?
  • 我需要将每个唯一 product_id 的数量和 sale_price 相乘,然后求总和。我也用 api 链接编辑了问题

标签: php laravel laravel-query-builder


【解决方案1】:

你可以使用selectRaw来做这样的事情:

$items = DB::table('bag')->where('bag.user_id' , $user_id)
            ->where('bag.order_id', 0)
            ->join('products','products.id','=','bag.product_id')
            ->selectRaw('*, (bag.quantity * products.sale_price) as totalPrice')
            ->get();

要得到所有的总和,你可以使用sum:

$sum=$items->sum('totalPrice');

【讨论】:

  • 我如何获取所有总价格的总和?这是为 bag 表中保存的每一行提供 totalPrice。
  • 我已更新我的答案以获得所有总价格的总和
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-16
  • 2019-01-23
  • 1970-01-01
  • 1970-01-01
  • 2019-04-06
相关资源
最近更新 更多