Hi,
i need to filter the most sold products and show later in a view, (top 10 most sold)
i have 3 tables:
- products (general product info) -> id | name
- invoice_items -> name | item_quantity | product_id
- saleorder_items -> name | item_quantity | product_id
as you may guess in products table i have my list of products and when a purchase is made it goes into invoice_items table or saleorder_items table according to customers invoice request.
if a product id is in both tables combine them and count up
so far i have done this:
$products = DB::table('products')
->leftJoin('invoice_items', 'products.id', '=', 'invoice_items.product_id')
->selectRaw('products.*, COALESCE(sum(invoice_items.item_quantity),0) sold')
->groupBy('products.id')
->orderBy('sold','desc')
->take(10)
->get();
above code works and i get a list of top 10 invoice_items product, however when i want to join saleorder_items table because there might be product with same id so i can count that as a total, it goes wrong and shows only the products which are in both table only...
$products = DB::table('products')
->leftJoin('invoice_items', 'products.id', '=', 'invoice_items.product_id')
->leftJoin('saleorder_items', 'products.id', '=', 'saleorder_items.product_id')
->selectRaw('products.*, COALESCE(sum(invoice_items.item_quantity + saleorder_items.item_quantity),0) sold')
->groupBy('products.id')
->orderBy('sold','desc')
->take(10)
->get();