2015-07-06 95 views
0

我有菜單項和菜單類別。類別被分配給菜單項。例如,'比薩'就在'晚餐'之下。Laravel列表中顯示的多個值

在我的菜單項列表中,儘量顯示列表視圖中的類別,但我無法弄清楚如何在菜單項列表中顯示類別名稱作爲循環。在列表上下文之外管理這些數據沒有問題。

這是我的菜單項控制器

public function index() { 
    $lists = Menu::orderBy('position')->orderBy('page_name')->paginate(20); 
    return view('auth.admin.menu.index') 
    ->with('title', "Menu") 
    ->with('lists', $lists); 
} 

循環是索引()。 。 。

@foreach ($lists as $list) 
… 
@endforeach 

模型是

public function menucats() { 
    return $this->belongsToMany('app\Menucat')->withTimestamps(); 
} 

public function menu() { 
    return $this->belongsToMany('app\Menu')->withTimestamps(); 
}    

所以我想實現應該是這樣的最終結果:

<table> 
    <thead> 
    <tr> 
     <th>id</th> 
     <th>Menu Items (Menu)</th> 
     <th>Category (Menucat)</th> 
    </tr> 
    </thead> 
    <tbody> 
    <tr> 
     <td>29</td> 
     <td>Pizza</td> 
     <td>Dinner</td> 
    </tr> 
    <tr> 
     <td>28</td> 
     <td>Ice Cream</td> 
     <td>Desert</td> 
    </tr> 
    <tr> 
     <td>27</td> 
     <td>Coffee</td> 
     <td>Hot Drinks</td> 
    </tr> 
    </tbody> 
</table> 

回答

1

根據註釋更新

經過重新 - 讀你的問題我不相信你需要更新你的模型。如果你想要的關係是很多menucats可以屬於很多menus

在你的控制器,你會怎麼做

public function index() { 
    $lists = Menu::with('menucats') 
       ->orderBy('position') 
       ->orderBy('page_name') 
       ->paginate(20); 
    return view('auth.admin.menu.index') 
    ->with('title', "Menu") 
    ->with('lists', $lists); 
} 

然後你的循環過程中它會被這樣的訪問。

@foreach($lists as $list) 
    ... 
    @foreach($list->menucats as $category) 
     {{ $category->name }} 
    @endforeach 
    ... 
@endforeach 

通過menucats根據註釋

再次更新爲組,我會得到所有menucats及其相關menus

在你的控制器中這樣的東西應該工作。分頁可能會很棘手。

public function index() { 
    $lists = Menucats::with(['menu' => function($q){ 
       $q->orderBy('position') 
       ->orderBy('page_name'); 
      ])->paginate(20); 

    return view('auth.admin.menu.index') 
    ->with('title', "Menu") 
    ->with('lists', $lists); 
} 

退房約束渴望負荷Querying Relations

+0

感謝下,我不知道該用()函數的!不改變模型不可能做到這一點?是否需要我改變模式? – cardi777

+0

@ cardi777我更新了我的答案。重新閱讀您的問題後,看起來您已經定義了多對多關係。如果是這種情況,您可以訪問我注意到的相關類別。 – whoacowboy

+0

非常感謝,我現在幾乎在那裏。因此,在這種情況下,按類別排序是不可能的? – cardi777