Here are my 3 tables:
Products : (id, product_name)
Purchase Product : (id, product_id, purchase_price, quantity)
Sales Product : (id, product_id, sales_price, quantity, purhase_price)
I want to find the products which are on the purchase list as well as the sales list. If it's not on it the sales list it should return NULL for sales value as well as quantity.
Here same product has different different purchase price so I need to track which purchase product has been sold. But with the group by it's showing the wrong sum.
What could be a possible error of my query?
Here's my query:
$products = DB::table('products')
->join('purchase_products','purchase_products.product_id','products.id')
->leftjoin("sales_products",function($join){
$join
->on("sales_products.purchase_price","purchase_products.purchase_price")
->on("sales_products.product_id","purchase_products.product_id");
})
->select('products.product_name','purchase_products.purchase_price',DB::raw("SUM(purchase_products.quantity) as purchase_quantity"),'sales_products.sales_price',DB::raw("SUM(sales_products.quantity) as sales_quantity"))
->groupby('products.id','purchase_products.purchase_price')
->get();