2017-02-01 138 views
1

我需要从两个不同的条件计算结果,从相同的关系,但它是作为相同的名称返回。Laravel多个withCount在相同的关系

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

我可以访问使用$model->requests_countwithCount,而是因为它的查询相同的关系,这似乎覆盖它:

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` 

我怎么能指定多个withCount名字?

回答

3

选项1

创建两个不同的关系:

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

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

,并利用它们:

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

选项2

创建withCount()类似方法将建立财产与自定义名称:

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; 
} 

并使用它:

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

选项1完美。非常感谢阿列克谢。 – Ben