Laravel 5 为什么收集->;where()返回索引号?
我相信这可能是一个简单的解决方案,但我似乎无法解决它 我试图使用Laravel的Laravel 5 为什么收集->;where()返回索引号?,laravel-5,collections,Laravel 5,Collections,我相信这可能是一个简单的解决方案,但我似乎无法解决它 我试图使用Laravel的where()子句来构建属于每个$student的$courses数组。我循环浏览每个$student,并过滤$courseRecords,根据学生代码查找匹配的课程 以下是我的示例代码片段: // Cycle through the students and add their relevant course details foreach( $students as $student ) { // Fi
where()
子句来构建属于每个$student
的$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;
}
然而,我得到的结果给出了每个学生的课程,但有一个领先的索引号(如下随机结果所示):
我似乎不明白为什么会这样。第一个条目(Id 0)是我期望的结果,但由于某些原因,其他每个结果似乎都会给我提供匹配的索引号$courseRecord
我试过使用$courses->all()代码>和$courses->toArray()代码>但这没有任何区别。从Laravel文档(我已经读过)中,它没有提到这种行为,这让我觉得我有什么不正确的地方
$students
和$courseRecords
都是一个集合。使用值()
$courses=$courseRecords->where('StudentId',$student->StudentCode)->value();
嗯,这是您试图为学生检索的所有课程吗?如果是。。为什么不使用雄辩的关系呢?你能分享结果数组而不是屏幕截图吗?还有$courseRecords->where('StudentId',$student->StudentCode)不带->get()
的代码>将返回查询生成器实例,请小心。