2017-09-22 53 views
1

我想在那裏我有一個關係查詢像這樣的基礎上laravel-5.4一個小應用程序:如何使用laravel收集幫助器方法?

$companies = Company::where('is_client', '=', 1) 
    // load count on distant model 
    ->with(['interactionSummaries.interaction' => function ($q) { 
     $q->withCount(['contactsAssociation' => function ($q) { 
      $q->whereHas('company', function ($q) { 
       $q->where('type', 'like', 'Investor'); 
      }); 
     }]); 
    }]) 
    ->get(); 

現在我想收集所有來自查詢生成和contact_association_counts其添加到個別公司收集爲此,我正在使用pluck,collapsesum方法,但我不知道它沒有按照需要進行計算。以下是截圖:

我得到收集的名單如下:

list of company

現在,我得到的屬性:

Attributes

現在的關係型數據:

relational data

現在交互數據,其中計數屬於:

Interaction data

因此,對於這個我想:

$companies = Company::where('is_client', '=', 1) 
    // load count on distant model 
    ->with(['interactionSummaries.interaction' => function ($q) { 
     $q->withCount(['contactsAssociation' => function ($q) { 
      $q->whereHas('company', function ($q) { 
       $q->where('type', 'like', 'Investor'); 
      }); 
     }]); 
    }]) 
    ->get() 
    ->transform(function ($company) { 
     $company->contacts_association_count = $company->interactionSummaries 
      ->pluck('interaction.contacts_association_count') 
      ->collapse() 
      ->sum(); 
     return $company; 
    }); 

但這並非計算計數,所有的計數來0

幫我解決這個問題。由於

回答

2

我相信你的問題是->collapse()看到您的示例->pluck('interaction.contacts_association_count')你應該有一個平坦的數組[1,2,3,4,5]如果你申請collapse()到一個平面陣列它返回一個空數組[]後的空隙陣列的總和爲0

$companies = Company::where('is_client', '=', 1) 
    // load count on distant model 
    ->with(['interactionSummaries.interaction' => function ($q) { 
     $q->withCount(['contactsAssociation' => function ($q) { 
      $q->whereHas('company', function ($q) { 
       $q->where('type', 'like', 'Investor'); 
      }); 
     }]); 
    }]) 
    ->get() 
    ->transform(function ($company) { 
     $company->contacts_association_count = $company->interactionSummaries 
      ->pluck('interaction.contacts_association_count') 
      //->collapse() 
      ->sum(); 
     return $company; 
    }); 

我希望它的工作......祝你好運!

+0

謝謝。有效! –