表 categories
字段
id,name,parent_id
模型 Category.php 加入
public function categories()
{
return $this->hasMany(Category::class, 'parent_id', 'id');
}
public function childrenCategories()
{
return $this->hasMany(Category::class, 'parent_id', 'id')->with('categories');
}
控制器里查询
$categories = Category::where('parent_id', '0')->with('childrenCategories')->get();
// 视图传 $categories
视图代码
<ul>
@foreach ($categories as $category)
<li data-id="{{ $category->id }}"><a href="{{ route('products.lists', $category->id) }}">{{ $category->name }}</a>
<ul>
@foreach ($category->childrenCategories as $childCategory)
@include('product._child_category', ['child_category' => $childCategory])
@endforeach
</ul>
</li>
@endforeach
</ul>
子视图 _child_category.blade.php
<li data-id="{{ $child_category->id }}">
<a href="{{ route('products.lists', $child_category->id) }}">{{ $child_category->name }}</a>
@if (count($child_category->categories) > 0)
<ul>
@foreach ($child_category->categories as $childCategory)
@include('product._child_category', ['child_category' => $childCategory])
@endforeach
</ul>
@endif
</li>