I'm trying of get the product most selled of each community by the suppliers, However I'm getting always the product 1. My goal is only get one product "the most selled" according the community of the supplier.
This is my db schema:
And this is my current query using Laravel:
$products = Purchase::select([
'purchases.supplier_id',
'purchases.id as purchId',
'suppliers.id as supliId',
'suppliers.community_id',
'purchase_details.product_id',
'purchase_details.qty',
'purchase_details.purchase_id',
])
->selectRaw('sum(purchase_details.qty) as sum')
->join('suppliers','purchases.supplier_id','suppliers.id')
->join('purchase_details','purchases.id','purchase_details.purchase_id')
->groupBy('suppliers.community_id')
->groupBy('purchase_details.product_id')
;
$sql = $products->toSql();
$result = \DB::table( \DB::raw("({$sql}) as sub") )
->mergeBindings($products->getQuery())
->groupBy('community_id')
->join('communities','sub.community_id','communities.id')
->leftJoin('products','sub.product_id','products.id')
->select('communities.name as communityName',
'products.name as productName')
->selectRaw('max(sub.sum) as total_ventas')
->get();
return $result;
Output:
[
{
"communityName": "Chunchos",
"productName": "Product 1",
"total_ventas": "1.00"
},
{
"communityName": "Colpas",
"productName": "Product 1",
"total_ventas": "4.00"
},
{
"communityName": "Punas",
"productName": "Product 1",
"total_ventas": "8.00"
}
]
SQL Query output:
select `communities`.`name` as `communityName`,
`products`.`name` as `productName`,
max(sub.sum) as total_ventas
from (select `purchases`.`supplier_id`,
`purchases`.`id` as `purchId`,
`suppliers`.`id` as `supliId`,
`suppliers`.`community_id`,
`purchase_details`.`product_id`,
`purchase_details`.`qty`,
`purchase_details`.`purchase_id`,
sum(purchase_details.qty) as sum from `purchases`
inner join `suppliers` on `purchases`.`supplier_id` = `suppliers`.`id`
inner join `purchase_details`
on `purchases`.`id` = `purchase_details`.`purchase_id`
where `purchases`.`deleted_at` is null
group by `suppliers`.`community_id`, `purchase_details`.`product_id`) as sub
inner join `communities` on `sub`.`community_id` = `communities`.`id`
inner join `products` on `sub`.`product_id` = `products`.`id`
group by `community_id`
Why my joins are not working?