Laravel 列表中显示的多对多值

Laravel many to many values shown in list

我有菜单项和菜单类别。类别分配给菜单项。例如,'pizza' 在 'dinner' 下。

在我的菜单项列表中,我想在列表视图中显示类别,但我不知道如何在我的菜单项列表中循环显示类别名称。我在列表上下文之外管理这些数据没有问题。

这是我的菜单项控制器中的 index()

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>

根据评论更新

重新阅读您的问题后,我认为您不需要更新模型。如果你想要的关系是很多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

下查看 Constraining Eager Loads