laravel - 循环遍历关系 Laravel

标签 laravel foreach relationship

堆栈溢出,

我想要实现的目标:

我想循环遍历数据库以找到所有(英雄)及其相关的(采访)。我还想提取每个采访的相关(故事)和(图像)。到目前为止,我可以 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/

相关文章:

mysql - 如何在 Laravel Eloquent 中使用 MIN 和 MAX sql 查询

mysql - 如何使用 laravel 通过分组获得值的总和

php - while 循环创建关联数组

sql-server - 使用查询或 SSIS 在 SQL 数据中查找 "regional"关系

mysql - 如何处理为多个用户存储多个值?

JavaScript forEach 语法和长度

java - Spring Mvc在Jsp中显示来自多个List的数据

SQL:这两个表之间存在什么样的关系(1:1、1:m、m:m、...)?

ruby-on-rails - Rails has_many :through association

php - 如何构建电子商务应用程序的数据库?