【问题标题】:How to get related laravel model of a related model如何获取相关模型的相关laravel模型
【发布时间】:2019-09-25 08:42:05
【问题描述】:

我正在制作餐厅菜单,其中每家餐厅都有自己的菜单项,这些菜单项属于一个类别(例如早餐、午餐……)

我的目标是当您访问特定餐厅时,它应该显示与菜单项相关联的类别,其中的菜单按这样分组。

  1. 早餐
    • 茶和蛋糕 - 10 美元
    • 咖啡和面包 - 15 美元
  2. 午餐
    • 米饭和鸡肉 - 45 美元
    • 鸡肉和薯条 - 30 美元

我的关系如下...

1 餐厅有很多菜单 |每个 Menu_Category 有很多 Menus

在我的模型中

餐厅模型

public function menus()
{
    return $this->hasMany('App\Menu');
}

菜单模式

public function restaurant()
{
    return $this->belongsTo('App\Restaurant');
}


public function category_type()
{
    return $this->belongsTo('App\Category', 'category_id');
}

类别模型

public function menus_type()
{
    return $this->hasMany('App\Menu','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');
    $p = 1;


    $categories = Category::with('menus_type')->get(); /* This is where I'm lost */

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

frontend.restaurant.show

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

          @if($category->id ===$restaurant->menus->id)
          <li>
              {{$category->name}}
              <ul>
                  @foreach($category->menus_type as $menu_key=>$menu)
                  <li>{{$menu->name}}</li> 
                  @endforeach
              </ul>
           </li>
          @endif

     @endforeach
    </ul>
@endif

它不工作!

【问题讨论】:

    标签: laravel laravel-5 eloquent orm


    【解决方案1】:

    RestaurantController 中保持简单。找出所有相关的菜单项并按类别分组。以下代码未经过测试,您可以试一试。

    $restaurant = Restaurant::findOrFail(1);
    $categories = $restaurant->menus->groupBy('category_id');
    

    现在,将它们提取到视图文件中

    @foreach($categories as $key => $category)
        {{ Category::query()->find($key)->name }}
        <ul>
            @foreach($category as $menu)
                <li>{{ $menu->name }}</li>
            @endforeach
        </ul>
    @endforeach
    

    【讨论】:

      猜你喜欢
      • 2018-10-12
      • 2016-05-26
      • 2016-08-30
      • 2018-05-31
      • 2014-12-05
      • 2014-02-12
      • 1970-01-01
      • 2020-05-25
      • 2020-03-22
      相关资源
      最近更新 更多