2015-07-06 94 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