Laravel -子类别显示在主类别下

0wi1tuuw  于 2023-04-13  发布在  其他
关注(0)|答案(4)|浏览(169)

你好

我有一个关于类别和子类别的问题
我有一张table,像:
ID-----姓名---- ParentID
1 ------- A ---------- 0
2 ------- B ---------- 0
3 ------- C --------- 1
我已经显示了A B C。但是我需要它像这样显示:
A
-- C
B
只是有问题,不找到这样做的方法(使子类别下的父)
注意:我在视图中成功地使用了make query,但我认为这并不好。
我想找到更好的方法
非常感谢

webghufk

webghufk1#

使用Eloquent,您可以使用hasMany()关系将表与其自身相关联。
尝试在模型上创建一个新方法,如下所示:

class Category extends Eloquent 
{

    ...

    public function children()
    {
        return $this->hasMany('Category','ParentId');   
    }
}

然后,您应该能够获得任何给定ID的子类别列表。

$categories = Category::where('ID','=','1')->with('children')->get();

或者,deczo在评论中建议的查询要简单得多,我建议使用这个。

Category::with('children')->find(1);
oaxa6hgo

oaxa6hgo2#

显示子、子和子类别-

型号

1.迁移以下类别表:

Schema::create('categories', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name');
    $table->tinyInteger('parent_id')->default(0);
    $table->timestamps();
});

1.输入您的类别和子类别,如以下表格结构:

+-------------+----------------------+----------+
| id          | name                 |parent_id |
+-------------+----------------------+----------+
|           1 | ELECTRONICS          |      0   |
|           2 | TELEVISIONS          |      1   |
|           3 | TUBE                 |      2   |
|           4 | LCD                  |      2   |
|           5 | PLASMA               |      2   |
|           6 | PORTABLE ELECTRONICS |      1   |
|           7 | MP3 PLAYERS          |      6   |
|           8 | FLASH                |      7   |
|           9 | CD PLAYERS           |      6   |
|          10 | 2 WAY RADIOS         |      6   |
+-------------+----------------------+----------+

控制器

  1. MySQL分层递归查询
$categories = DB::table('categories as c1')
    ->leftJoin('categories as c2','c2.parent_id','=','c1.id')
    ->leftJoin('categories as c3','c3.parent_id','=','c2.id')
    ->leftJoin('categories as c4','c4.parent_id','=','c3.id')
    ->select('c1.id as c1_id','c1.name as c1_name','c2.id as c2_id','c2.name as c2_name','c3.id as c3_id','c3.name as c3_name','c4.id  as c4_id','c4.name as c4_name')
    ->where('c1.parent_id','=',0)
    ->get();

输出:

+-----------------+--------------------------+------------------+-----------------+
|c1_id| c1_name   | c2_id| c2_name           | c3_id| c3_name   | c4_id| c4_name  |
+-----------------+--------------------------+------------------+-----------------+
| 1 | ELECTRONICS | 2 | TELEVISIONS          | 3 | TUBE         | NULL  |
| 1 | ELECTRONICS | 2 | TELEVISIONS          | 4 | LCD          | NULL  |
| 1 | ELECTRONICS | 2 | TELEVISIONS          | 5 | PLASMA       | NULL  |
| 1 | ELECTRONICS | 6 | PORTABLE ELECTRONICS | 7 | MP3 PLAYERS  | 8   | FLASH |
| 1 | ELECTRONICS | 6 | PORTABLE ELECTRONICS | 9 | CD PLAYERS   | NULL  |
| 1 | ELECTRONICS | 6 | PORTABLE ELECTRONICS | 10| 2 WAY RADIOS | NULL  |
+-------------+--------------------------------------+--------------+-------+

1.然后,将$categories值放入Array中。

$all_categories = [];
$category_c1_id = '';
$category_c2_id = '';
$category_c3_id = '';
$category_c4_id = '';
$c1_id = -1;
$c2_id = -1;
$c3_id = -1;
$c4_id = -1;
foreach ($categories as $k=>$category){
    if($category->c1_id != $category_c1_id){
        $c1_id = $c1_id +1;
        $all_categories[$c1_id]['id'] = $category->c1_id;
        $all_categories[$c1_id]['name'] = $category->c1_name;
        $c2_id = -1;
    }
    if($category->c2_id != $category_c2_id && $category->c2_id <> NULL){
        $c2_id = $c2_id +1;
        $all_categories[$c1_id]['children'][$c2_id]['id'] = $category->c2_id;
        $all_categories[$c1_id]['children'][$c2_id]['name'] = $category->c2_name;
        $c3_id = -1;
    }
    if($category->c3_id != $category_c3_id && $category->c3_id <> NULL){
        $c3_id = $c3_id +1;
        $all_categories[$c1_id]['children'][$c2_id]['children'][$c3_id]['id'] = $category->c3_id;
        $all_categories[$c1_id]['children'][$c2_id]['children'][$c3_id]['name'] = $category->c3_name;
        $c4_id = -1;
    }
    if($category->c4_id != $category_c4_id && $category->c3_id <> NULL){
        $c4_id = $c4_id +1;
        $all_categories[$c1_id]['children'][$c2_id]['children'][$c3_id]['children'][$c4_id]['id'] = $category->c4_id;
        $all_categories[$c1_id]['children'][$c2_id]['children'][$c3_id]['children'][$c4_id]['name'] = $category->c4_name;
    }
    $category_c1_id = $category->c1_id;
    $category_c2_id = $category->c2_id;
    $category_c3_id = $category->c3_id;
    $category_c4_id = $category->c4_id;
}
return $all_categories;

输出:

$categories = [
  ['id' => 1, 'name' => 'TV & Home Theather'],
  ['id' => 2, 'name' => 'Tablets & E-Readers'],
  ['id' => 3, 'name' => 'Computers', 'children' => [
    ['id' => 4, 'name' => 'Laptops', 'children' => [
      ['id' => 5, 'name' => 'PC Laptops'],
      ['id' => 6, 'name' => 'Macbooks (Air/Pro)']
    ]],
    ['id' => 7, 'name' => 'Desktops'],
    ['id' => 8, 'name' => 'Monitors']
  ]],
  ['id' => 9, 'name' => 'Cell Phones']
];

查看

1.现在显示在选择产品上传选项

<div class="form-group">
    <label>Select Categories</label><br/>
    @foreach($categories as $category)
        @php($category = (object)$category)
        <div class="form-check">
            <label class="form-check-label" for="{{$category->id}}">
                {{ Form::checkbox('category_ids[]', $category->id, null, array('id'=>$category->id)) }}
                {{$category->name}}
            </label>
            @if(isset($category->children))
                @foreach($category->children as $subcategory)
                    @php($subcategory = (object)$subcategory)
                    <div class="form-check" style="margin-left: 15px;">
                        <label class="form-check-label" for="{{$subcategory->id}}">
                            {{ Form::checkbox('category_ids[]', $subcategory->id, null, array('id'=>$subcategory->id)) }}
                            {{$subcategory->name}}
                        </label>
                        @if(isset($subcategory->children))
                            @foreach($subcategory->children as $subsubcategory)
                                @php($subsubcategory = (object)$subsubcategory)
                                <div class="form-check" style="margin-left: 15px;">
                                    <label class="form-check-label" for="{{$subsubcategory->id}}">
                                        {{ Form::checkbox('category_ids[]', $subsubcategory->id, null, array('id'=>$subsubcategory->id)) }}
                                        {{$subsubcategory->name}}
                                    </label>
                                </div>
                            @endforeach
                        @endif
                    </div>
                @endforeach
            @endif
        </div>
    @endforeach
</div>

和ON菜单选项

<ul class="nav primary clone-main-menu toggle-slide-menu" id="mercado_main" data-menuname="Main menu" >
  @foreach($categories as $category)
      <li class="menu-item menu-item-has-children item-megamenu" >
          <a href="#" title="Digital & Electronics" class="link-term mercado-item-title">{{$category['name']}}</a>
          <div class="wrap-megamenu">
              <div class="megamenu-content min-height-510 bg-vertical-digital">
                  @if(isset($category['children']))
                      <div class="row">
                          @foreach($category['children'] as $subcategory)
                              <div class="col-lg-3 col-md-3">
                                  <div class="wrap-vertical-nav">
                                      <h2 class="menu-title"><a href="#" class="link-term">{{$subcategory['name']}}</a></h2>
                                      @if(isset($subcategory['children']))
                                          <ul>
                                              @foreach($subcategory['children'] as $subcategory)
                                                  <li class="menu-item"><a href="#" class="link-term">{{$subcategory['name']}}</a></li>
                                              @endforeach
                                          </ul>
                                      @endif

                                  </div>
                              </div>
                          @endforeach
                      </div>
                  @endif
              </div>
          </div>
      </li>
  @endforeach
</ul>
fafcakar

fafcakar3#

对我来说,我必须改变一些像这样的事情

<ul>
    <li><a href="{{ route('index') }}" class="menu-active">Home</a></li>
    <li><a href="#">Product Categories</a>
        <ul>
            @foreach($categories as $category)
                <li><a href="#">{{$category['name']}}</a>
                    @if(isset($category['children']))
                        <ul>
                            @foreach($category['children'] as $subCategory)
                                <li>
                                    <a href="#" class="link-term">{{$subCategory['name']}}</a>
                                    @if(isset($subCategory['children']))
                                        <ul>
                                            @foreach($subCategory['children'] as $subSubCategory)
                                                <li><a href="#">{{$subSubCategory['name']}}</a>
                                                    @if(isset($subSubCategory['children']))
                                                        <ul>
                                                            @foreach($subSubCategory['children'] as $subSubSubCategory)
                                                                <li><a href="#">{{$subSubSubCategory['name']}}</a></li>
                                                            @endforeach
                                                        </ul>
                                                    @endif
                                                </li>
                                            @endforeach
                                        </ul>
                                    @endif
                                </li>
                            @endforeach
                        </ul>
                    @endif
                </li>
            @endforeach
        </ul>
    </li>
    <li><a href="{{ route('shop')}}">Shop</a></li>
    <li><a href="{{ route('contact')}}">Contact Us</a></li>
</ul>
4uqofj5v

4uqofj5v4#

我认为你应该做一个树结构,如果你想获取类别的所有子类别深,当返回类别,你可以让你的逻辑内追加新的属性....使您的应用程序更高的性能...这种方式采取两个查询到您的数据库(:

相关问题