3

I am looking for the Eloquent, or raw sql, to get the sums of two of my ->withCount. I need to be able to do this without having to ->get() the records, it needs to be implemented using Eloquent, not laravels Collection methods.

I have the following:

$owners = User::active() ->where(function($q){ $q->whereHas('primaryContractOwner') ->orWhereHas('primaryVendorOwner'); }) ->withCount([ 'primaryContractOwner', 'primaryVendorOwner' ]); 

I need to get the sum of primary_contract_owner count and primary_vendor_owner count. I tried the following but I am getting primary_contract_owner_count column not found

// This one throws the error $owners = User::active() ->where(function($q){ $q->whereHas('primaryContractOwner') ->orWhereHas('primaryVendorOwner'); }) ->withCount([ 'primaryContractOwner', 'primaryVendorOwner' ]) ->select(['user.*', DB::raw('primary_contract_owner_count + primary_vendor_owner')]); 
1
  • Why do you need the sum in the query? Commented Dec 17, 2018 at 20:58

2 Answers 2

1

https://laravel.com/docs/5.7/eloquent-relationships#counting-related-models

I believe your counts will be called primaryContractOwner_count and primaryVendorOwner_count. You can run the query without the DB::raw part to check.

Sign up to request clarification or add additional context in comments.

Comments

0

You can use the collection method reduce as below

$owners->reduce(function($carry,$item){ return $carry+$item->primaryContractOwner_counter; },0); 

for more please check the reduce documentation: https://laravel.com/docs/6.x/collections#method-reduce

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.