Reputation: 35
i've a 3 Models : Pizzerie , Pizze , Ingredients each has his own relationships
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');
}
}
I'm looking for a query that allow me to loop in my view like this
@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
Can't figure out how to get it :/
Upvotes: 2
Views: 311
Reputation: 332
I cant comment to Margus Pala's answers :( but your query should like
$data = \App\pizzerie::with('pizze. ingredienti')->get();
because of the eager loading problem, this is important problem (too many query in loop)
Eager loading in documentation
Upvotes: 1
Reputation: 8663
Try this, it will get the next relation Collection in each of the foreach loops.
@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
Upvotes: 0