简体   繁体   English

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

[英]get categories which has subcategories using laravel

I'm retrieving data from two tables which are categories and subcategories. 我正在从两个表中检索数据,这两个表是类别和子类别。

categories cat_id contains inside the subcategories table as a foreign key. 类别cat_id包含在子类别表中作为外键。

Here is my code from Category model: 这是我的类别模型代码:

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

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

Here is my code from SubCategory model: 这是我来自SubCategory模型的代码:

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

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

This is how I retrieve data from my controller: 这是我从控制器中检索数据的方式:

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

This is how my .blade.php part looks like: 这是我的.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

As above html structure: I am going to construct a tree view if any category has sub categories else show the category without a tree view . 如上html结构所示:如果任何类别具有子类别,则我将构造一个树形视图,否则显示没有树形视图的类别。 But I get all the categories with or without subcategories inside a tree view.. Can anyone suggest a way please... 但是我在树状视图中获得了所有带有或不带有子类别的类别。任何人都可以建议一种方法吗?

Just wrap the nested ul in an if: 只需将嵌套的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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM