How to get most sold products in Laravel?

Viewed 498

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:

  • order status == 'approved'
  • If there is a product_price_after_discount ignore the originall product price and count this.

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();
1 Answers

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.

Related