Laravel: 如何在我的视图中使用分组依据?
Laravel: How can I use Group By within my view?
我正在尝试获取所有学生,然后按毕业年份对他们进行分组。在我看来,我想要一个年度头条:
<h2>2016</h2>
<ul>
<li>Last, First</li>
...
</ul>
<h2>2017</h2>
<ul>
<li>Last, First</li>
...
</ul>
我相信我很接近,但不确定 "Laravel way"。数据看起来不错 - 例如,查询 getting/grouping 正确,我认为我的困难在于理解如何循环遍历集合。
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
类似于:
$studentsByYear = $students;
foreach ($studentsByYear as $year => $students) {
echo "<h2>$year</h2>";
echo "<ul>";
foreach ($students as $student) {
echo "<li>".$student->name."</li>";
}
echo "</ul>";
}
我正在尝试获取所有学生,然后按毕业年份对他们进行分组。在我看来,我想要一个年度头条:
<h2>2016</h2>
<ul>
<li>Last, First</li>
...
</ul>
<h2>2017</h2>
<ul>
<li>Last, First</li>
...
</ul>
我相信我很接近,但不确定 "Laravel way"。数据看起来不错 - 例如,查询 getting/grouping 正确,我认为我的困难在于理解如何循环遍历集合。
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
类似于:
$studentsByYear = $students;
foreach ($studentsByYear as $year => $students) {
echo "<h2>$year</h2>";
echo "<ul>";
foreach ($students as $student) {
echo "<li>".$student->name."</li>";
}
echo "</ul>";
}