如何在Laravel的导航菜单中列出Category - Subcategory

时间:2018-04-29 16:04:13

标签: php laravel eloquent query-builder

如何在Laravel的导航菜单中列出Category - Subcategory?

我的查询如下。

id  Title    parent_id
1   cat1     1
2   cat2     1
3   cat3     2
4   cat4     3

1 个答案:

答案 0 :(得分:0)

将这些功能添加到您的模型中

public function children()
{
    return $this->hasMany(Category::class, 'parent_id', 'id');
}

public function parent()
{
    return $this->belongsTo(Category::class, 'parent_id', 'id');
}

然后在你看来:

@foreach ($categories as $category)

   @if($category->parent_id == 0)

      @include('categories.view', $category)

    @endif
@endforeach

categories.view.blade 文件

的内容
<li id="{{$category->id}}" data-jstree='{"icon":"fa {{$category->icon}}"}'>

  <a href="#">{{ $category->name }}</a>

  @if ($category->children()->count() > 0)
    <ul>
      @foreach($category->children as $category)
         @include('categories.view', $category)
     @endforeach
   </ul>
  @endif
</li>