使用laravel获取具有子类别的类别

时间:2015-07-20 05:47:20

标签: php mysql laravel eloquent laravel-5

我正从两个表中检索数据,这两个表是类别和子类别。

类别cat_id在子类别表中包含外键。

以下是我的类别模型代码:

class Category extends Model
{
    protected $table = 'categories';

    public function subcategories()
    {
        return $this->hasMany(Subcategory::class, 'categories_id');
    }
}

这是我的SubCategory模型代码:

class Subcategory extends Model
{
    protected $table = 'sub_categories';

    public function category()
    {
        return $this->belongsTo(Category::class, 'categories_id');
    }

这是我从控制器检索数据的方法:

$treeView = Category::with(['subcategories'])->get();

这就是我的.blade.php部分的样子:

@foreach($treeView as $category)
    @if($category->has('subcategories'))
        <li class="treeview">
            <a href="#"><i class="fa fa-link"></i> <span>{{ $category->category_name }}</span>
                <i class="fa fa-angle-left pull-right"></i></a>
            <ul class="treeview-menu">
                @foreach($category->subcategories as $subcategory)

                    <li class=""><a href="#">{{$subcategory->sub_category_name}}</a></li>

                @endforeach
            </ul>
        </li>
    @else
        <li><a href="#"><i class="fa fa-link"></i> <span>{{ $category->category_name }}</span></a></li>
    @endif

@endforeach

如上所述html结构:如果任何类别具有子类别,我将构建树视图,否则显示没有树视图的类别。但是我在树视图中得到了所有带或不带子类别的类别。任何人都可以建议一种方式...

1 个答案:

答案 0 :(得分:1)

将嵌套的ul包装在if:

@if($category->subcategories->count())
  <ul class="treeview-menu">
    @foreach($category->subcategories as $subcategory)
      <li class=""><a href="#">{{$subcategory->sub_category_name}}</a></li>
    @endforeach
  </ul>
@endif