2016-12-13 111 views
0

我正在创建一个网站,将订单分配给员工。 我将新订单分配给分配给订单数量最少的员工。Laravel选择最小值

我当前的代码,发现员工:

$employees=User::whereHas('employee', function ($q) use ($company) { 
     $q->where('company_id', $company->id); 
    })->get(); 
    $min='999'; 
    foreach ($employees as $employee) 
    { 
     if(Order::where('assigned_to_employee',$employee->id)->count()<$min) 
     { 
      $assign_id=$employee->id; 
      $min=Order::where('assigned_to_employee',$employee->id)->count(); 
     } 
    } 

我觉得有一个更好的办法做到这一点这样的建议是值得欢迎的。 另外,如果我这样做的方式是好的,我如何分配给$ min一个最大的int值?

感谢

回答

0

我不知道我完全理解,但我认为你会从下面的,如果你正在使用Laravel 5.3中获益。您应该能够使用withCount和orderBy的组合来获取订单数量最少的员工列表。

User::withCount('employee')->orderBy('employee_count', 'asc')->first(); 
+0

谢谢,问题是,分配给员工的订单存储在订单表中,而不是存储在员工表中。 – user3844579