微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

类别-子类别系统

如何解决类别-子类别系统

id:1 || name:category_1 || parent_id:NULL
id:2 || name:subcategory_1.1 || parent_id:1
id:3 || name:subcategory_1.2 || parent_id:1
id:4 || name:category_2 || parent_id:NULL
id:5 || name:subcategory_2.1 || parent_id:4
id:6 || name:subcategory_2.2 || parent_id:4
id:7 || name:category_3 || parent_id:NULL

大家好,我已经建立了这种类型的数据库来管理类别和子类别。 我想设置一个循环,允许我只显示 category_3 但我不知道该怎么做。 实际上,我想排除所有有孩子的父母。

仅查看我使用的父母:


    @foreach($categories as $parent)
      <option value="{{ $parent->id }}">{{$parent->name}}</option>
    @endforeach

查看父母和孩子:


    @foreach($categories as $parent)
    <option value="{{ $parent->id }}">{{$parent->name}}</option>
      @if($parent->children)
        @foreach($parent->children as $children
        <option value="{{ $children->id }}">{{$children->name}}</option>
        @endforeach
      @endif
    @endforeach

类别控制器


      public function create()
        {
          $categories = Category::with('children')->whereNull('parent_id')->where('status','=',1)->get();
            return view('backend.category.create')->with([
              'categories'  => $categories
            ]);
        }

类别(模型)


      public function children()
        {
            return $this->hasMany('App\Models\Category','parent_id');
        }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。