所以我遇到了一个问题,我要设置所有东西并测试它们之间的关系,但无法真正解决我如何正确使用嵌套类别正确输出导航的问题,这就是我的类别模型
public function products() {
return $this->belongsToMany(Product::class);
}
public function parent()
{
return $this->belongsTo(Category::class, 'parent_id');
}
public function children()
{
return $this->hasMany(Category::class, 'parent_id');
}
public function getRouteKeyName()
{
return 'slug';
}
有效,我通过修补匠进行了测试,它可以正确地使孩子和父母 所以如何显示它,这是我用来显示类别的部分内容,然后我试图在视图中调用自己,有点像递归,现在有了孩子,但是它在请求时卡住了并且赢得了页面没有加载,所以我假设它不能像这样
@if(count($categories))
<ul class="list-group">
@foreach($categories as $category)
<li class="list-group-item"><a href="/{{ $category->slug }}">{{ $category->name }}</a></li>
@include('layouts.categories', ['categories' => $category->children])
@endforeach
</ul>@endif
这是我获取类别的方法,我这样做是为了对所有视图可用,但我假设此查询是可以修改的
View::composer('*', function ($view) {
$view->with('categories', Category::all());
});
我想要的结果是这个
Men
-Men's Shoes
Women
-Women's Shoes
答案 0 :(得分:1)
如果类别过多,您将遇到N + 1问题。
将此添加到您的模型中:
public function allChildren()
{
return $this->children()->with('allChildren');
}
然后您的作曲家应该是:
View::composer('*', function ($view) {
$view->with('categories', Category::with('allChildren')->all());
});
如果由于多个查询而崩溃,这可能会为您解决问题。