获取具有子类别的类别使用laravel [英] get categories which has subcategories using laravel

查看:109
本文介绍了获取具有子类别的类别使用laravel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm retrieving data from two tables which are categories and subcategories.

类别 cat_id 包含子类别表作为外键。

categories cat_id contains inside the subcategories table as a foreign key.

这是我的类别模型中的代码:

Here is my code from Category model:

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

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

这是我从SubCategory模型中的代码:

Here is my code from SubCategory model:

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();

这是我的 .blade.php 部分看起来像:

This is how my .blade.php part looks like:

@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结构:如果任何类别具有子类别,我将构造树视图,否则显示没有树视图的类别。但是我可以在树状视图中获得所有类别或不带子类别。任何人都可以提出一种方式请求...

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 . But I get all the categories with or without subcategories inside a tree view.. Can anyone suggest a way please...

推荐答案

只需将嵌套的ul包装到一个if:

Just wrap the nested ul in an 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

这篇关于获取具有子类别的类别使用laravel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆