php - 我如何在 Laravel 中显示分组值

标签 php laravel laravel-5 eloquent

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

  • 午餐
    • 鸡肉和薯条
    • 米饭
  • 早餐
    • 咖啡

所以我的数据库中有 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'));
}

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

This is what is returned from the $menu variable

结果已经分组

Expand results set with relationships

现在我的问题出在 View 上,当我尝试获取结果时出现错误。

   @if($menus)
   <ul>
     @foreach($menus as $m)
       <li>
         {{$m->name}}
       </li>
     @endforeach
   </ul>
   @endif

ErrorException (E_ERROR).

Property [name] does not exist on this collection instance.

最佳答案

也迭代内循环。 'groupBy()' 创建另一个以 category_id 作为键的数组。

@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

关于php - 我如何在 Laravel 中显示分组值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58074873/

相关文章:

php - Laravel:如果您不提交或回滚您手动启动的事务怎么办?

php - Laravel chmod(/var/dev/project/storage/oauth-public.key) : Operation failed: Operation not permitted

laravel - Html 标签在 ckeditor 之后显示

php - 如何减去类型不同的行的同一列?

php - Laravel 根据距离对用户集合进行排序

php - 我在 Laravel 上收到 'General error: 1364',说我没有用户名的默认值,有人可以帮我吗?

php - Laravel created_at 返回对象代替数据库中的日期格式?

php - 如何转义输入但未转义保存到数据库中

php - Dockerfile 在 FROM 之后没有进行 RUN 更改

php - Symfony 4 使用用户实体的基本 http 身份验证