代码之家  ›  专栏  ›  技术社区  ›  Riples

为什么collection->where()返回索引号?

  •  0
  • Riples  · 技术社区  · 6 年前

    我相信这可能是一个简单的解决办法,但我似乎解决不了。

    我想用拉维的 where() 子句来生成 $courses 属于每个人的 $student . 我骑自行车穿过每一个 $学生 过滤掉 $courseRecords 根据学生代码查找匹配的课程。

    下面是我的示例代码片段:

    // Cycle through the students and add their relevant course details
    foreach( $students as $student ) {
    
        // Find matching courses to the student
        $courses = $courseRecords->where( 'StudentId', $student->StudentCode );
    
        // Add the course array to the student record
        $student->Courses = $courses;
    
    }
    

    然而,我得到的结果给了我每个学生的课程,但是有一个领先的索引号(随机结果如下所示):

    enter image description here

    我好像搞不懂为什么会这样。第一个条目(Id 0)是我所期望的结果,但是由于某些原因,其他每个结果似乎都给出了 $courseRecord .

    我试过用 $courses->all(); $courses->toArray(); 但这没什么区别。从Laravel文档(我读过)来看,它没有提到这种行为,这使我认为我有不正确的地方。

    $students $课程记录 都是收藏品。

    1 回复  |  直到 6 年前
        1
  •  0
  •   Jonas Staudenmeir    6 年前

    使用 values() :

    $courses = $courseRecords->where('StudentId', $student->StudentCode)->values();