2016-11-24 31 views
0

我有一個與自身相關的類別模型。一個類別可能有多個子類別。每個類別可以是子類別,也可以是父類別。Laravel從自我相關模型嵌套的foreach循環以樹狀顯示

在刀片中,我想顯示在層次結構或樹中。但我不知道如果每個類別都有孩子,我該如何檢查和顯示。我循環使用foreach,但我真的不能想到子循環。是否可以顯示如下。

1. Electronic 
    1.1 Entertainment 
     1.1.1 TV 
      1.1.2 DVD 
      1.1.2.x there may be more or not 
2.Fashion 
2.1 Man 
    2.1.1 Top 
    2.1.2 Bottom 
+1

發佈您的代碼。 [如何提出問題](http://stackoverflow.com/help/mcve) – Manish

+0

檢查了這個https://github.com/etrepat/baum我建議你使用它,而不是 – Michel

回答

0

在您的模型上創建關係。你可以讓自己喜歡的關係

public function childs(){ 
    return $this->hasMany('Category', 'id', 'parent_id'); 
} 

,可以作爲Category::with('childs') 訪問孩子的考慮u能做出這樣的:

@foreach($categories as $c) 
    {{$c->title}} 
@if($c->childs->count()>0) 
    @foreach($c->childs as $child) 
    $child->title 
    @endforeach 
@endif 
@enforeach