Sử dụng Laravel 5.1, tôi đang cố tạo danh sách menu từ bảng danh mục MySQL. Nhà cung cấp dịch vụ của tôi trả về dữ liệu, nhưng tôi không hiểu cách tạo các danh mục con trong vòng lặp foreach. Khi tôi thực hiện vòng lặp, chỉ có hàng cuối cùng của truy vấn con được trả về. Mọi hướng dẫn sẽ được đánh giá cao.Laravel trả lại con của cha mẹ trong cùng một bảng
loại Bảng
id | cat_name | cat_parent_id
--- | --------------| -------------
1 | Parent Cat 1 | NULL
2 | Parent Cat 2 | NULL
3 | Child Cat 1 | 2
4 | Child Cat 2 | 2
5 | Parent Cat 3 | NULL
6 | Child Cat 3 | 5
mong muốn Kết quả
Parent Cat 1
Parent Cat 2
Child Cat 1
Child Cat 2
Parent Cat 3
Child Cat 3
viewComposerServiceProvider.php
public function boot()
{
$this->composeTopCategoryNavigation();
$this->composeSubCategoryNavigation();
}
private function composeTopCategoryNavigation()
{
view()->composer('partials.header', function($view)
{
$view->with('top_cats', Category::whereNull('cat_parent_id')->orderBy('cat_name', 'asc')->get());
});
}
private function composeSubCategoryNavigation()
{
view()->composer('partials.header', function($view)
{
$view->with('sub_cats', Category::whereNotNull('cat_parent_id')->orderBy('cat_name', 'asc')->get());
});
}
tiêu đề xem
<ul>
@foreach ($top_cats as $top_cat)
<?php $top_cat_slug = str_slug($top_cat->cat_name, "-"); ?>
<li>{{ $top_cat->cat_name }}
@foreach ($sub_cats as $sub_cat)
@if ($sub_cat->cat_parent_id === $top_cat->id)
<ul>
<li{{ $sub_cat->cat_name }}</li>
</ul>
@endif
@endforeach
</li>
@endforeach
</ul>