嵌套关系Laravel Eloquent查询

时间:2015-04-27 08:34:08

标签: nested eloquent relationship laravel-5

我有3个模特:Pizzerie,Pizze,每个成分都有自己的关系

class Pizzerie extends Model {
  protected $table = 'pizzerie';
  public function pizze()
  {
      return $this->hasMany('App\Pizze', 'pizzerie_id');
  }
}

class Pizze extends Model {
  protected $table = 'pizze';
  public function ingredienti()
  {
      return $this->belongsToMany('App\Ingredienti', 'pizze_ingredienti');
  }
  public function pizzeria()
  {
      return $this->belongsTo('App\Pizzerie');
  }
}

class Ingredienti extends Model {
  protected $table = 'ingredienti';
  public function pizze()
  {
      return $this->belongsToMany('App\Pizze', 'pizze_ingredienti');
  }
}

我正在寻找一个允许我在我的视图中循环的查询

@foreach($data as $pizzeria)
<p>{{ $pizzeria->name }} Has pizze: </p>
  @foreach($pizzeria as $pizze)
  <p>{{ $pizza->name }} Has ingredients: </p>
    <ul>
    @foreach($pizza as $ingredient)
    <li>{{ $ingredient->name }}</li>
    @endforeach
    </ul>
  @endforeach
@endforeach

无法弄清楚如何获得它:/

2 个答案:

答案 0 :(得分:1)

我无法评论Margus Pala的答案:(但你的查询应该是

$data = \App\pizzerie::with('pizze. ingredienti')->get();

由于急切的加载问题,这是一个重要的问题(循环查询太多)

Eager loading in documentation

答案 1 :(得分:0)

试试这个,它会在每个foreach循环中得到下一个关系Collection。

@foreach($data as $pizzeria)
<p>{{ $pizzeria->name }} Has pizze: </p>
  @foreach($pizzeria->pizze as $pizze)
  <p>{{ $pizza->name }} Has ingredients: </p>
    <ul>
    @foreach($pizze->ingredienti as $ingredient)
    <li>{{ $ingredient->name }}</li>
    @endforeach
    </ul>
  @endforeach
@endforeach