亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在 Laravel 中顯示分組值

如何在 Laravel 中顯示分組值

PHP
ITMISS 2022-01-24 13:10:56
我正在嘗試顯示按類別分組的餐廳菜單,例如...午餐雞肉和薯條米早餐茶咖啡所以我的數據庫中有 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'));}當我轉儲它時,它看起來很好。結果已分組現在我的問題出在視圖上,當我嘗試獲取結果時,我得到了一個錯誤。   @if($menus)   <ul>     @foreach($menus as $m)       <li>         {{$m->name}}       </li>     @endforeach   </ul>   @endif錯誤異常 (E_ERROR)。此集合實例上不存在屬性 [名稱]。
查看完整描述

1 回答

?
www說

TA貢獻1775條經驗 獲得超8個贊

也迭代內循環。'groupBy()' 用category_idas 鍵創建另一個數組。


@if($menus)

 <ul>

 @foreach($menus as $category_id=>$outer)

  @foreach($outer as $k=>$inner)

   <li>

      {{$category_id}}: {{$inner->name}}

   </li>

   @endforeach

 @endforeach

 </ul>

 @endif

更新了您的查詢以從類別中獲取


$categories = Category::with('menus_type')->get();

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

在你看來


@if($categories ?? false)

 <ul>

 @foreach($categories ?? [] as $cat_key=>$category)

  <li>

      {{$category->name}}

  </li>

  <li>

  <ul>

  @foreach($category->menus_type as $menu_key=>$menu)

  <li>

      {{$menu->name}}

  </li> 

  @endforeach

  </ul>

  </li>

 @endforeach

 </ul>

 @endif


查看完整回答
反對 回復 2022-01-24
  • 1 回答
  • 0 關注
  • 250 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號