Laravel:明智地显示类别和产品树

时间:2018-07-02 05:40:58

标签: laravel laravel-5

我想按树状显示类别和产品,这意味着后续产品将显示在类别下,依此类推。为此,我制作了此脚本,该脚本仅显示类别,但下面没有产品。下面是我的控制器脚本:

$data['sitecategories'] = $this->generateSiteCategorySubcategory(-1);

在同一控制器中,我创建了函数:

public function generateSiteCategorySubcategory($startAt) {
        if ($children = Sitecategory::getCategorySubcategory($startAt)) {
            $thisLevel = array();
            foreach ($children as $child) {
                $thisLevel[$child->id] = $child;
                $thisLevel[$child->id]->children = $this->generateSiteCategorySubcategory($child->id);
            }
            return $thisLevel;
        }
    }

在刀片中,我编写了在选择框中呈现产品和类别的信息:

<select name="categoryid"  class="form-control customSelect" >                                                                                        
 @foreach ($sitecategories as $sitecategory)                                                                                    
 @php if($sitecategory->parentCategoryId != '-1'){ $catName = "--". 
 $sitecategory->categoryName;                                                                                        
 } else { $catName = $sitecategory->categoryName;                                                                                     
}                                                                                    
@endphp
<option value="{{$sitecategory->id}}">{{$catName}}</option>
@endforeach
</select>

下面是数据库表结构:

id parentCategoryId categoryName状态


1 -1平板电脑和手机1

2 -1时尚1

10 1手机1

12 1片1

15 2女子1

运行脚本后,它只会在选择框中显示类别,但类别下不会出现任何产品。

1 个答案:

答案 0 :(得分:1)

尝试一下。

$categoryProducts = \DB::table('categories)
             ->join('products','products.category_id','=','categories.id')
             ->select('categories.*','products.*')
             ->get();

     dd($categoryProducts);