堆栈溢出,
我想要实现的目标:
我想循环遍历数据库以找到所有(英雄)及其相关的(采访)。我还想提取每个采访的相关(故事)和(图像)。到目前为止,我可以 dd($heroes) 并且可以看到数组正确地捕获了每个英雄的采访,并且每个采访都有相关的图像和故事。我如何正确地循环它?
错误
Invalid argument supplied for foreach() (View: /Users/plastics1509moore/Desktop/elephant_gin/resources/views/administration/index.blade.php)
这就是我所做的:
Controller :
$heroes = Hero::with('Interview', 'Interview.stories', 'Interview.images')->orderBy('position', 'asc')->get();
模型关系:
英雄:
public function Interview()
{
return $this->hasOne('App\Interview', 'heroInt_id');
}
面试:
public function relationships()
{
return $this->belongsTo('App\Hero');
}
public function stories()
{
return $this->hasMany('App\InterviewStory');
}
public function images()
{
return $this->hasMany('App\InterviewImage');
}
采访图片:
public function relationships()
{
return $this->belongsTo('App\Interview');
}
采访故事
public function relationships()
{
return $this->belongsTo('App\Interview');
}
HTML:
循环:
@foreach($heroes as $hero)
@foreach($hero->Interview as $story)
<div>{{$story->id}}</div>
@endforeach
@endforeach
最佳答案
您无法循环播放 Interview,因为这是 hasOne
关系。您可能想做的是
@foreach($heroes as $hero)
@foreach($hero->interview->stories as $story)
<div>{{$story->id}}</div>
@endforeach
@endforeach
关于laravel - 循环遍历关系 Laravel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33919113/