Laravel雄辩地获得相关表的列之和

问题描述

我很难说清楚我的购物车价格, 这是我的桌子:

cart_products:
- cart_id
- product_id
- quantity

products:
- price

一个购物车可以有多个cart_products,每个cart_products有一个相关产品

我正在从购物车模型发出请求,我正在尝试获取购物车的总价(cart_products.quantity * products.price)。

这是我的查询:

Cart::select('cart.*',\DB::raw('IFNULL(SUM(products.price*cart_products.quantity),0) AS cart_price'))
        ->leftJoin('cart_products','cart.id','=','cart_products.cart_id')
        ->join('products','cart_products.product_id','products.id');

这样做的时候,我确实得到了预期的结果,但是排除了所有不包含产品的购物车,我希望将它们包括在内。

我如何包含它们?还是有更好的方法(我见过withCount方法,但我无法使其正常运行)?

解决方法

另一种方法是在购物车模型中设置虚拟关系并像计算购物车价格一样

class Cart extends Model
{
    public function price()
    {
        return $this->hasOne(CartProducts::class,'cart_id')
            ->join('products as p','product_id','=','p.id')
            ->groupBy('cart_id')
            ->selectRaw('cart_id,IFNULL(SUM(products.price*cart_products.quantity),0) as cart_price');
    }
}

要获取购物车的价格数据,您可以查询为

Cart::with('price')->get()->sortByDesc('price.cart_price');
,

我终于设法使用原始SQL进行另一种方式:

        Cart::select('cart.*',\DB::raw('(SELECT IFNULL(SUM(products.price*cart_products.quantity),0) from cart_products join products on products.id = cart_products.product_id where cart_products.cart_id = cart.id) AS cart_price'));

感谢大家的帮助!

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...