2017-02-01 24 views
1

同じ関係から2つの異なる条件の結果を数える必要がありますが、同じ名前として返されます。同じ関係のLaravel multiple 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_countを使用してwithCountにアクセスすることができますが、それは同じ関係を照会しているため、それを上書きするように見える:

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

をを作成します。カスタム名とプロパティを構築するのような方法:

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