Laravel 获取 table 与 eloquent 相关的列的总和
Laravel get sum of related table's columns with eloquent
我在计算 eloquent 购物车的价格时遇到了一些问题,
这是我的表格:
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'));
感谢大家的帮助!
我在计算 eloquent 购物车的价格时遇到了一些问题, 这是我的表格:
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'));
感谢大家的帮助!