如何获得相关模型的相关Laravel模型

时间:2019-09-25 08:42:05

标签: laravel laravel-5 eloquent orm

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

我的目标是,当您访问特定的餐厅时,它应该显示与菜单项链接的类别,并且其中的菜单按此分组。

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

我的关系如下...

  
    
      

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

    
  

在我的模型中

餐厅模型

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

它不起作用!

1 个答案:

答案 0 :(得分:0)

id, username, password, dbname, tablename = map(request.form.get, ('token', 'username', 'password', 'dbname', 'tablename')) 中保持简单。找出所有相关的菜单项,并按类别对其进行分组。以下代码尚未经过测试,您可以尝试一下。

RestaurantController

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

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