0
經過數小時的試用和失敗後,我在我的刀片模板內的foreach循環中卡住了,我需要一些幫助。Laravel foreach issues
我的控制器
public function menue() {
$restaurants = User::with('articles')->get();;
return view('pages.menues')->withRestaurants($restaurants);
}
我的foreach
@foreach($restaurants as $restaurant)
<div class="panel panel-default">
<div class="panel-heading">
@foreach($restaurant->articles as $article)
{{$article->title}}
<span class="float-right">{{$article->published_at}}</span>
@endforeach
</div>
<div class="panel-body">
@foreach($restaurant->articles as $article)
{{$article->body}}
@endforeach
{{$restaurant->name}}
</div>
</div>
@endforeach
這就是我想要循環槽:我的刀片TEMPL的
{
"id":1,
"name":"Sam",
"email":"[email protected]",
"created_at":"2016-07-26 15:03:51",
"updated_at":"2016-07-27 15:39:55",
"articles":[
{
"id":1,
"user_id":1,
"title":"Monday Afternoon",
"body":"got it",
"created_at":"2016-07-27 15:31:05",
"published_at":"2016-07-27 15:30:00",
"excerpt":null,
"updated_at":"2016-07-27 15:31:05"
},
{
"id":3,
"user_id":1,
"title":"Good Morning Wednesday",
"body":"lorem ipsum",
"created_at":"2016-07-27 11:38:37",
"published_at":"2016-07-27 11:38:00",
"excerpt":null,
"updated_at":"2016-07-27 11:38:37"
},
{
"id":4,
"user_id":1,
"title":"Good Morning Thursday",
"body":"lorem ipsum ",
"created_at":"2016-07-27 11:39:14",
"published_at":"2016-07-28 14:38:00",
"excerpt":null,
"updated_at":"2016-07-27 11:39:14"
},
{
"id":5,
"user_id":1,
"title":"Wednesday Afternoon",
"body":"Hallo Welt",
"created_at":"2016-07-27 14:55:00",
"published_at":"2016-07-27 14:54:00",
"excerpt":null,
"updated_at":"2016-07-27 14:55:00"
}
]
}
結果是,而不是四個職位,我只得到2個職位。他們每個人都包含其他職位。如何在我的視圖中單獨顯示所有4個帖子?
不相關的問題,但你應該考慮[預先加載關係(https://laravel.com/docs/5.1/eloquent-relationships#eager-loading)代替只通過餐廳,然後迭代'$餐廳 - >文章' - 這會給您的數據庫帶來不必要的請求,也被稱爲「N + 1問題」PS:更糟糕的是,您正在做兩次(您有兩個單獨的foreach循環) –