Chris Xanthou
Chris Xanthou

Reputation: 67

Eloquent Aggregates

Hi i have that query is it possible to insert additional count that counts self the Customer table rows? something like {{count($customers)}}

Also i have join the Services table on model, how can i add SUM on specific column of services table on the query above? for example Service->sum('price');

      $customers = Customer::query((['id', 'name', 'plate']))
       
      ->search($this->search,['id', 'name', 'plate'])
      ->withCount('services')     
      ->orderBy($this->sortBy,$this->sortDirection,['id', 'name', 'plate'])
      ->paginate($this->perPage,['id', 'name', 'plate']);
     
      return view('livewire.customers.show',['customers'=>$customers])

Upvotes: 0

Views: 415

Answers (1)

IGP
IGP

Reputation: 15786

You do not need to change anything. The paginator already knows the total count.

$customers->total() should give you the count you're looking for.

As for the sum on a related column, Laravel added somewhat recently the withAggregates functions (withSum, withAvg). You should be able to get the total price by adding

->withSum('services as total_price', 'price')

to your query

Upvotes: 1

Related Questions