Laravel:如何在我的视图中使用Group By?

时间:2016-06-25 14:37:09

标签: laravel-5.2 laravel-blade

我想让所有学生,然后按毕业年份分组。在我看来,我希望有一年的标题:

<h2>2016</h2>
<ul>
    <li>Last, First</li>
    ...
</ul>

<h2>2017</h2>
<ul>
    <li>Last, First</li>
    ...
</ul>

我相信我很接近,但不确定“Laravel方式”。数据看起来很好 - 就像在查询中正确获取/分组一样,我认为我的斗争是理解如何遍历集合。

MyController.php

public function index()

{
    $students = Student::all()->groupBy('grad_year');

    return view('student.index', compact('students'));
}

在我看来,我可以看到我得到了这个:

MyView.blade.php

{{dd($students)}}

Collection {#178 ▼
    #items: array:2 [▼
        2016 => Collection {#173 ▼
            #items: array:3 [▼
                0 => Student {#180 ▶}
                1 => Student {#181 ▶}
                2 => Student {#182 ▶}
            ]
        }
        2017 => Collection {#172 ▶}
    ]
}

以下是我的视图,以获得我想要的输出。

MyView.blade.php

@foreach ($collection as $year => $students)
    <p>{{$year}}</p>

    <ul class="list-unstyled">
        @foreach($students as $student)
            <li><a href="">{{ $student->last_name }}, {{ $student->first_name }}</a></li>
        @endforeach
    </ul>
@endforeach

1 个答案:

答案 0 :(得分:5)

类似的东西:

$studentsByYear = $students;

foreach ($studentsByYear as $year => $students) {
 echo "<h2>$year</h2>";
 echo "<ul>";
   foreach ($students as $student) {
     echo "<li>".$student->name."</li>";
   }
 echo "</ul>";
}