Laravel 购物车总和基于 2 个不同表的输入

我有 2 张桌子、袋子(购物车)和产品。我将用户添加的数量保存在错误表中,将销售价格保存在产品表中。我需要获取每件商品的 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 相乘,然后求其总和


长风秋雁
浏览 89回答 1
1回答

慕侠2389804

你可以使用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');
打开App,查看更多内容
随时随地看视频慕课网APP