2015-11-23 58 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循环是循环的开始** –