作为树的Laravel和无限类别

时间:2018-02-13 18:15:35

标签: php laravel laravel-5.6

如何显示所有类别,包括sub,sub,sub(..)类别,我有简单的表格:

enter image description here

和我的模特:

class Category extends Model
{
    public $fillable = [
        'parent_id',
        'name',
        'description'
    ];

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

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

我想得到:

<ul>
  <li>Category
    <ul>
      <li>Category 1.1</li>
      <li>Category 1.2</li>
    </ul>
  </li>
  (...)
</ul>

1 个答案:

答案 0 :(得分:1)

此实用方法适用于 n n 子女数量的类别

首先创建一个部分视图category.blade.php文件,该文件以递归方式调用自身以加载其子项

<li>
       @if ($category->children()->count() > 0 )
           <ul>
               @foreach($category->children as $category)

                       @include('category', $category) //the magic is in here

               @endforeach
           </ul>

       @endif
</li>

然后在主视图中添加此代码,以递归方式加载所有子项

  <ul>
        @foreach ($categories as $category)

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

                @include('category', $category)

            @endif
        @endforeach

    </ul>