2015-11-23 52 views
0

我工作在App類似於CRM應用(客戶關係管理)檢索Laravel關係最小

我有一個分配給用戶

//check if contract end or not and active or inactive 
    // and first_date_for_service < now() 
    $ms= MaintenanceService::join('cus_contract','cus_contract.id','=','maintenance_service.contract_id') 
     ->where('cus_contract.status','=','active') 
     ->where('cus_contract.contract_end_at','>',Carbon::now()) 
     ->where('maintenance_service.user_id', Auth::user()->id) 
     ->where('maintenance_service.first_date_for_service','<', Carbon::now()) 
     ->get(); 

現在我有下面的代碼,得到的$ms陣列的$ms陣列所以我將循環遍歷它作爲以下

for($x = 0; $x< count($ms);$x++) { 
    // here i get all notifications for $ms[$x] in each loop using Eloquent 
     return count($ms[$x]->notifications); 
    } 

上面的代碼運作良好,但我需要首先取最小值,爲電子xample

在第一環路通知 和在第二計數的計數爲。

但我需要的分鐘在第一所以當return $ms[$x]->notifications; 我需要返回攜帶分鐘計數在我們的例子

有沒有辦法實現這個數組?

謝謝你的時間。

+0

您是否只需要具有最低通知次數的行或您是否需要按通知排序的所有項目? – user2479930

+0

不,我需要所有項目才能獲得每個客戶的最低通知數 –

回答

1

我想你嘗試MaintenanceService項目由有排序notifications關係計數?

// check if contract end or not and active or inactive 
// and first_date_for_service < now() 
$ms= MaintenanceService::join('cus_contract','cus_contract.id','=','maintenance_service.contract_id') 
    ->where('cus_contract.status','=','active') 
    ->where('cus_contract.contract_end_at','>',Carbon::now()) 
    ->where('maintenance_service.user_id', Auth::user()->id) 
    ->where('maintenance_service.first_date_for_service','<', Carbon::now()) 
    ->get() 
    // sort all by the notifications count 
    ->sortBy(function($ms) { 
     // assuming 'notifications' is a relationship within the MaintenanceService model 
     return count($ms->notifications); 
    }); 

檢查出更多關於集合heresortBy方法。

編輯: 當然你還需要sortByDesc HIGH => LOW和sortBy爲LOW => HIGH。

+0

完美的謝謝。 –

+3

@JustUser請注意,這遭受「N + 1」問題。對於每個維護服務對象,您將運行單獨的查詢以獲取該對象的通知。您可以使用[預先加載]緩解此問題(http://laravel.com/docs/5.1/eloquent-relationships#eager-loading)。將'with()'方法添加到查詢中:'MantenanceService :: with('notifications') - > join ...'。 – patricus

+0

@patricus謝謝你的建議,我會:) –

-1

爲了獲得與列的最低值的元素,你可以使用可用的min()方法上收藏

<?php 

$ms = MaintenanceService::join('cus_contract','cus_contract.id','=','maintenance_service.contract_id') 
    ->where('cus_contract.status','=','active') 
    ->where('cus_contract.contract_end_at','>',Carbon::now()) 
    ->where('maintenance_service.user_id', Auth::user()->id) 
    ->where('maintenance_service.first_date_for_service','<', Carbon::now()) 
    ->get(); 

$lowest = $ms->min('notifications'); 

上收集更多信息: http://laravel.com/docs/5.1/collections

所有可用的收集方法: http://laravel.com/docs/5.1/collections#available-methods


旁註

要通過雄辯結果迭代你可以做一個foreach上,因爲它把它作爲一個數組需要時:

<?php 

foreach($ms as $element) { 
    $notifications = $element->notifications; 
} 
+1

我認爲那裏誤解我不需要最小列如果我想最小 列我可以做這個'$毫秒[$ x] - >通知 - >分鐘();' 第二件事'通知'是雄辯的方法不是列 **我需要得到'通知'關係的最小計數for循環是循環的開始** –