循环关系Laravel

时间:2015-11-25 14:30:24

标签: laravel foreach relationship

Stackoverflow,

我想要完成的事情:

我想通过数据库循环找到所有(英雄)与他们相关的(面试)。我还希望每次采访与其相关的(故事)和(图片)。到目前为止,我可以dd($英雄),我可以看到阵列正确地抓住每个英雄与他们的采访,每个采访都有它的相关图像和故事。如何正确循环?

错误

Invalid argument supplied for foreach() (View: /Users/plastics1509moore/Desktop/elephant_gin/resources/views/administration/index.blade.php)

这就是我所做的:

控制器:

$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');
}

InterviewImage:

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

InterviewStory

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

HTML

循环:

    @foreach($heroes as $hero)
       @foreach($hero->Interview as $story)
         <div>{{$story->id}}</div>
        @endforeach    
    @endforeach

2 个答案:

答案 0 :(得分:6)

您无法循环采访,因为这是一种hasOne关系。您可能想要做的是

@foreach($heroes as $hero)
   @foreach($hero->interview->stories as $story)
     <div>{{$story->id}}</div>
    @endforeach    
@endforeach

答案 1 :(得分:1)

我认为你的问题是因为不遵循laravel“假设”。在文档中:

  

此外,Eloquent假设外键应该有   值匹配父项的id列。换句话说,Eloquent   将在user_id列中查找用户id列的值   电话记录。如果您希望关系使用值   除了id之外,您可以将第三个参数传递给hasOne方法   指定自定义键:

     

return $this->hasOne('App\Phone', 'foreign_key', 'local_key');

英雄的身份是什么?如果它与id不同,则必须添加local_key名称。