我有无限的类别、子类别、子子类别等等。
结构:
main
--main1
-----main2 ( child of main1 )
-----main3 ( child of main1 )
--main4
test
我的代码:
在Category.php model
public function categories()
{
return $this->hasMany(Category::class);
}
public function childrenCategories()
{
return $this->hasMany(Category::class);
}
在index.blade.php:
<select>
@foreach ($categories as $category)
<option value="{{ $category->id }}">{{ $category->category_name }}</option>
@foreach ($cat->childrenCategories as $childCategory)
@include('partials._child_categroy', ['child_category' => $childCategory])
@endforeach
@endforeach
</select>
在 _child_categroy.blade.php 中
<option value="{{ $child_category->id }}">--- {{ $child_category->category_name }}</option>
@if ($child_category->categories)
@foreach ($child_category->categories as $childCategory)
@include('partials._child_categroy', ['child_category' => $childCategory])
@endforeach
@endif
到目前为止一切都很好,但是当我打开调试器时,每个类别级别都有三个查询,存在循环!这是我的问题,如果我的链变得越来越大,那么 foreach 将会增加,这对性能不利!
请问有什么建议吗?
MM们