【问题标题】:Foreach loop not going through correctlyForeach 循环未正确通过
【发布时间】:2015-07-13 11:08:26
【问题描述】:

我有一个表格来标记员工的出勤情况,HR 填写该表格会循环到每个当前员工。我需要它来显示数据库中标记出勤的当前值,否则它应该是空白的。

在我的控制器中,我查询现有结果:

$results = Attendance::where('Sdate', '=', date("Y-m-d", strtotime($TheDate))) ->get();

然后遍历它们以获取员工详细信息:

foreach($results as $result)
{
    $contractors = DB::table('contractors') ->where('contractors.AreaPosition', '=', $department) ->where('PRN', '!=', $result->PRN) ->get(); $employees = DB::table('current_employees') ->where('current_employees.AreaPosition', '=', $department) ->where('PRN', '!=', $result->PRN) ->get(); $showEmployees = array_merge($contractors, $employees);
}

这应该排除在该日期保存了出勤记录的所有员工,但它似乎没有正确循环。它将排除一些结果,但不是全部。如果我返回 results 变量,我会得到正确的记录列表,因此我知道该部分工作正常。

在我看来,我希望实现的目标是:

@foreach($attendance as $results)

Show form where there's an existing record for this date and department

@endforeach



@foreach($employees as $employee)

Show form for all employees in this department (but should exclude results where there is a record in attendance)

@endforeach

【问题讨论】:

    标签: laravel laravel-5 laravel-form


    【解决方案1】:

    您的代码的问题是您将结果保存在变量中而不是数组中。 您的解决方案是将数据存储在数组中

    foreach($results as $result)
    {
        $contractors[] = DB::table('contractors') ->where('contractors.AreaPosition', '=', $department) ->where('PRN', '!=', $result->PRN) ->get(); $employees = DB::table('current_employees') ->where('current_employees.AreaPosition', '=', $department) ->where('PRN', '!=', $result->PRN) ->get(); $showEmployees = array_merge($contractors, $employees);
    }
    

    尝试打印承包商数组,看看会发生什么。我希望这可行

    【讨论】:

      【解决方案2】:

      这是在 Laracasts 上为我解答的。

      我需要做的是创建一个要检查的变量列表(员工编号)

          $PRNs = Attendance::where('Sdate', '=', date("Y-m-d", strtotime($TheDate)))->lists('PRN');
      

      然后使用 Laravel 的 whereNotIn,检查列表。

          $contractors = DB::table('contractors')
              ->where('contractors.AreaPosition', '=', $department)
              ->whereNotIn('PRN', $PRNs)
              ->get();
      

      【讨论】:

        猜你喜欢
        • 2015-07-04
        • 1970-01-01
        • 1970-01-01
        • 2017-11-24
        • 1970-01-01
        • 1970-01-01
        • 2019-02-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多