I have this query:
public static function totalByAgent(int $agentId) { return PropertyListing::select( DB::raw('SUM(property_listing.rental) as rental'), DB::raw('SUM(property_listing.sale) as sale'), 'property_category.name as category_name', 'property_category.id as category_id' )->join( 'property_category', 'property_category.id', 'property_listing.category_id' )->where('agent_id', $agentId)->groupBy('property_category.id')->get(); }
With this query I obtain the sum of properties for sale and sum of properties to rent group by property categories. But If some property have only properties for sale and 0 to rent I obtain 0 in sum of rents.
I tried adding:
->having('sale', '>', 0)->get()
after groupBy. this hides the rents if they had.
Any idea?
Best regards
Advertisement
Answer
Finally this query works for me:
return Property::published()->select(DB::raw('SUM(property.rental) as rental'), DB::raw('SUM(property.sale) as sale'), 'property_category.name as category_name', 'property_category.id as category_id') ->join('property_category', 'property_category.id', 'property.category_id') ->whereExists(function ($query) use ($agentId){ $query->select('property_listing.agent_id') ->from('property_listing') ->whereRaw('property.id = property_listing.property_id') ->where('property_listing.agent_id', $agentId); })->published() ->groupBy('property_category.id')->get();