2017-12-07 7 views
2

나는 Laravel 5.2 프로젝트에서 다음 Eloquent 쿼리가 :Laravel 수집 뽑은

ctry val 
at 1 
au 5 
br 1 

Eloquent 호출이 세 행의 컬렉션을 생성합니다 원시 쿼리는이 출력을 생성

$regsByCtryCollection = Organisation::join('countries_currencies', 'countries_currencies.id', '=', 'organisations.country_id') 
    ->select(DB::raw('DISTINCT LCASE(countries_currencies.country_code) AS ctry, COUNT(organisations.id) AS val')) 
    ->groupBy('ctry') 
    ->get(); 

을 (원시 쿼리 출력과 일치) :

Collection {#791 ▼ 
    #items: array:3 [▼ 
    0 => Organisation {#777 ▼ 
     #table: "organisations" 
     #hidden: [] 
     ........ 
     #attributes: array:2 [▶] 
     #original: array:2 [▼ 
     "ctry" => "at" 
     "val" => 1 
     ] 
     #relations: array:5 [▶] 
     ........ 
    } 
    1 => Organisation {#778 ▶} 
    2 => Organisation {#779 ▶} 
    ] 
} 

나는 다음 삭제이

$regsByCtry = $regsByCtryCollection->pluck('ctry', 'val')->map(function($country, $value) { 
    return [ 
     "hc-key" => $country, 
     "value" => $value 
    ]; 
})->values()->toJson(); 

그리고 값 중 하나처럼 Highmaps의 값과 형식을 따 난이 얻을 :

[ 
    {"hc-key":"br","value":1}, 
    {"hc-key":"au","value":5} 
] 

왜 첫 번째 항목이 삭제지고 있습니까?

{"hc-key":"at","value":1} 

하지만 그냥이 컬렉션에, 나는 다른 두 Eloquent 쿼리를이 같은 프로세스를 사용하고 예상대로 작동합니다.

또한 I의이 같은 개체들의 어레이의 모든 값을 합계 :

$regsTotal = array_sum($regsByCtryCollection->pluck('val')->toArray()); 

그리고 합산 된 모든 세 개의 레코드를 포함하여, 정확한 값을 얻기 :

$regsTotal = 7; 

답변

1

문제가 pluck('ctry', 'val'). 값이 & ctryval이 키로 반환됩니다. 쿼리 결과에서 at & 의 값은 1입니다. 그래서 그것 중 하나가 다른 것으로 대체되고 있습니다.

pluck('val', 'ctry')->map(function($value, $country)

시도

Reference

락 앤 롤
+0

! 고맙습니다! – TheRealPapa