2017-08-14 69 views
0

我有一個authors集合,它與posts集合具有多對多關係。該posts集合具有category場可以是,例如,「懸疑」,「戲劇」,「行動」等Laravel Mongo GroupBy以有效的方式計算

我需要的category領域都要經過我的整個posts收集和團體,也有相關的計數。

這是我到目前爲止有:

$authors = Author::where('active', true)->get(); 

     foreach ($authors as $author){ 
      foreach ($author->posts()->groupBy('category')->get() as $data){ 

       // Do some logic 

      } 
     } 

基本上我期待的輸出與category一個數組作爲鍵和計數的值。所以,如果我做$a['Drama']它給了我多少次作者寫了一個職位與該類別。

我可以通過在上面的循環邏輯中工作來弄明白,但看起來效率不高。我應該看看聚合嗎?如果有的話可以讓我開始嗎?

回答

0

試試這個:

use Illuminate\Support\Collection; 
use Illuminate\Support\Facades\DB; 

$authors = DB::collection('authors') 
    ->where('active', true) 
    ->get(); 

// Laravel >= 5.3 would return collection instead of plain array 
$authors = is_array($authors) ? Collection::make($authors) : $authors; 

$authors->map(function ($author) { 
    return $author 
     ->posts() 
     ->groupBy('category') 
     ->get() 
     ->map(function ($collection) { 
      return $collection->count(); 
     }); 
});