Laravel Eloquent group by pivot table&关系

时间:2016-04-18 08:29:58

标签: laravel eloquent pivot-table

我有这个平台,我正在为foodtruck活动创建。有一些参展商参加了几个活动。每个foodtruck都有自己的菜肴菜单,分为几类。

问题/我想要实现的目标

  

我想为每个事件制作一个菜单,循环遍历所有事件   参展商(谁参加),然后按类别展示菜肴。

     

像这样;

     

/菜单/ {事件ID}

     

菜类1

     
      
  • 来自参展商A的菜
  •   来自参展商B的
  • 菜肴
  •   
     

菜类2

     
      
  • 来自exh A的菜
  •   
  • 来自exh C的菜
  •   
  • 来自exh D的菜
  •   
     

...

模型

活动模型

class Event extends Model
{
    protected $table = "events";

    public function exhibitors()
    {
        return $this->belongsToMany('App\Exhibitor', 'events_exhibitors');
    }

菜模型

class Dish extends Model
{
    //

    protected $table = "dishes";    


    public function category()
    {
        return $this->hasOne('App\Category', 'id', 'category_id');
    }

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

参展商模型

class Exhibitor extends Model
{
    protected $table = "exhibitors";

    public function events()
    {
        return $this->belongsToMany('App\Event', 'events_exhibitors');
    }

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

数据库结构

有一个数据透视表可以记录哪些食物去哪些事件。到目前为止,我认为(希望)我的关系正在发挥作用。我希望这张图片足够显示;

DB structure

我尝试了什么

我尝试过几件事,但我认为我对Laravel雄辩的见解缺乏理解这个问题背后的逻辑。

$dishes = Event::where('id', $id)
            ->with(['exhibitors.dishes' => function($q) {
            $q->select('dishes.dish_data');
        }])->get();

或者

$dishes = Event::with(array('exhibitor.dish') => function($query) use ($sub){
            $query->where('name',$sub);}))->get();

我完全不知道如何通过Eloquent实现这一目标,或者在视图中如何实现这一点。

1 个答案:

答案 0 :(得分:0)

尝试这样的事情:

它将获得与活动相关的所有参展商的ID。 然后它将获得所有类别,其中连接的菜肴具有参展商ID中的参展商数据。

类别模型

class Category extends Model
{
    protected $table = "categories";    


    public function dishes()
    {
        return $this->hasMany('App\Dish', 'category_id');
    }
}

控制器操作

$event = Event::findOrFail($id);

$exhibitorIds = $event->exhibitors()->select('exhibitors.id')->get()->pluck('id')->all();

$categories = Category::whereHas('dishes', function($query) use ($exhibitorIds) {
    $query->whereIn('exhibitor_id', $exhibitorIds);
})->with(['dishes' => function($query) use ($exhibitorIds) {
    $query->whereIn('exhibitor_id', $exhibitorIds);
}])->get();

return view('events.menu', compact('event', 'categories') );

查看

@foreach($categories as $category)
<h2>{{ $category->name }}</h2>
<ul>
   @foreach($category->dishes as $dish)
       <li>{{ $dish->dish_data }}</li>
   @endforeach
</ul>
@endforeach
相关问题