0

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

1
  • Did you test the sql query directly in your database? without Eloquent. Then try to pass it to Eloquent.
    – pmiranda
    Jun 17, 2019 at 20:20

1 Answer 1

0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.