2017-08-14 64 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(); 
     }); 
});