8

I need to count the results from two different conditions, from the same relationship, but it's being returned as the same name.

Model::where('types_id', $specialism_id) ->withCount(['requests' => function ($query) { $query->where('type', 1); }]) ->withCount(['requests' => function ($query) { $query->where('type', 2); }]) 

I can access the withCount using $model->requests_count, but because it's querying the same relationship, it appears to overwrite it:

select count(*) from `requests` where `requests`.`id` = `model`.`id` and `type` = '1') as `requests_count`, (select count(*) from `requests` where `requests`.`id` = `model`.`id` and `type` = '2') as `requests_count` 

How can I specify the name for multiple withCount?

0

2 Answers 2

20

You can now do it like this

Model::where('types_id', $specialism_id) ->withCount(['requests as requests_1' => function ($query) { $query->where('type', 1); }, 'requests as requests_2' => function ($query) { $query->where('type', 2); }]) 
Sign up to request clarification or add additional context in comments.

Comments

9

Option 1

Create two different relationships:

public function relationship1() { return $this->hasMany('App\Model')->where('type', 1); } public function relationship2() { return $this->hasMany('App\Model')->where('type', 2); } 

And use them:

Model::where('types_id', $specialism_id)->withCount(['relationship1', 'relationship2']) 

Option 2

Create withCount() like method which will build property with custom names:

public function withCountCustom($relations, $customName) { if (is_null($this->query->columns)) { $this->query->select([$this->query->from.'.*']); } $relations = is_array($relations) ? $relations : func_get_args(); foreach ($this->parseWithRelations($relations) as $name => $constraints) { $segments = explode(' ', $name); unset($alias); if (count($segments) == 3 && Str::lower($segments[1]) == 'as') { list($name, $alias) = [$segments[0], $segments[2]]; } $relation = $this->getHasRelationQuery($name); $query = $relation->getRelationCountQuery( $relation->getRelated()->newQuery(), $this ); $query->callScope($constraints); $query->mergeModelDefinedRelationConstraints($relation->getQuery()); $column = $customName; <---- Here you're overriding the property name. $this->selectSub($query->toBase(), $column); } return $this; } 

And use it:

Model::where('types_id', $specialism_id) ->withCountCustom(['requests' => function ($query) { $query->where('type', 1); }], 'typeOne') ->withCountCustom(['requests' => function ($query) { $query->where('type', 2); }], 'typeTwo') 

Comments