如何在 Laravel 中显示分组值

我正在尝试显示按类别分组的餐厅菜单,例如...

  • 午餐

    • 鸡肉和薯条

  • 早餐

    • 咖啡

所以我的数据库中有 3 个表,餐厅、类别和菜单

类别模型

class Category extends Model

{

    protected $fillable = [

        'name'

    ];


    /**

     * @return \Illuminate\Database\Eloquent\Relations\HasMany

    */

    public function menus_type()

    {

        return $this->hasMany('App\Menu','category_id');

    }

}

型号菜单


class Menu extends Model

{

    protected $fillable = [

        'name',

        'price',

        'description',

        'photoPath',

        'restaurant_id',

        'category_id',

    ];


    /**

     * Menu belongs to Restaurant

     */

    public function restaurant()

    {

        return $this->belongsTo('App\Restaurant');

    }


    /**

     * Menu belongs to category type 

     */

    public function category_type()

    {

        return $this->belongsTo('App\Category', 'category_id');

    }


}

餐厅控制器


public function show($slug, RestaurantRepository $repository){

      if(! $restaurant = $repository->get(['slug' => $slug], with(['cuisines','user', 'photos', 'thumbs', 'region', 'ratings.user']))) return abort('404');


      $menus=Menu::with(['category_type'])->where('restaurant_id',$restaurant->id)->get()->groupBy('category_id');


       return view('frontend.restaurant.show', compact('restaurant', 'p','menus'));

}

当我转储它时,它看起来很好。

http://img3.mukewang.com/61ee34f90001a56a02350101.jpg

结果已分组

http://img1.mukewang.com/61ee35050001edcc03600631.jpg

现在我的问题出在视图上,当我尝试获取结果时,我得到了一个错误。


   @if($menus)

   <ul>

     @foreach($menus as $m)

       <li>

         {{$m->name}}

       </li>

     @endforeach

   </ul>

   @endif

错误异常 (E_ERROR)。


此集合实例上不存在属性 [名称]。


ITMISS
浏览 244回答 1
1回答

www说

也迭代内循环。'groupBy()' 用category_idas 键创建另一个数组。@if($menus)&nbsp;<ul>&nbsp;@foreach($menus as $category_id=>$outer)&nbsp; @foreach($outer as $k=>$inner)&nbsp; &nbsp;<li>&nbsp; &nbsp; &nbsp; {{$category_id}}: {{$inner->name}}&nbsp; &nbsp;</li>&nbsp; &nbsp;@endforeach&nbsp;@endforeach&nbsp;</ul>&nbsp;@endif更新了您的查询以从类别中获取$categories = Category::with('menus_type')->get();return view('frontend.restaurant.show', compact('restaurant', 'p','categories '));在你看来@if($categories ?? false)&nbsp;<ul>&nbsp;@foreach($categories ?? [] as $cat_key=>$category)&nbsp; <li>&nbsp; &nbsp; &nbsp; {{$category->name}}&nbsp; </li>&nbsp; <li>&nbsp; <ul>&nbsp; @foreach($category->menus_type as $menu_key=>$menu)&nbsp; <li>&nbsp; &nbsp; &nbsp; {{$menu->name}}&nbsp; </li>&nbsp;&nbsp; @endforeach&nbsp; </ul>&nbsp; </li>&nbsp;@endforeach&nbsp;</ul>&nbsp;@endif
打开App,查看更多内容
随时随地看视频慕课网APP