[英]How to get most sold products in Laravel?
My database structure:我的数据库结构:
products
-- name
-- price
-- qty
orders
-- user_id
-- status ... etc
order_product
-- order_id
-- product_id
-- qty
-- product_price_after_discount ( nullable )
I need to get most sold products with total_sells_of_product
when:在以下情况下,我需要使用total_sells_of_product
获得最畅销的产品:
status == 'approved'
订单status == 'approved'
product_price_after_discount
ignore the originall product price and count this.如果有product_price_after_discount
忽略原始产品价格并计算它。MY wrong shut:我的错误关闭:
$topSellingProducts = Product::selectRaw('
products.id,
products.trade_name,
products.company_name
')
->leftJoin('order_product','order_product.product_id','=','products.id')
->where('status','approved')
->groupBy('products.id')
->orderByDesc('total_sales')
->get();
If you want to consider the quantity in the order when calculating the most sold product:如果您想在计算最畅销产品时考虑订单中的数量:
DB::table('products')
->select([
'products.id',
'products.trade_name',
'products.company_name',
DB::raw('SUM(order_product.qty) as total_sales'),
DB::raw('SUM(IFNULL(product_price_after_discount, products.price) * order_product.qty) AS total_price'),
])
->join('order_product', 'order_product.product_id', '=', 'products.id')
->join('orders', 'order_product.order_id', '=', 'orders.id')
->where('orders.status','approved')
->groupBy('products.id')
->orderByDesc('total_sales')
->get();
And if you want to consider every product in an order once, then replace SUM(order_product.qty) as total_sales
with COUNT(*) as total_sales
.如果您想一次性考虑订单中的每个产品,请将SUM(order_product.qty) as total_sales
,将COUNT(*) as total_sales
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.