gpt4 book ai didi

laravel - 循环遍历关系 Laravel

转载 作者:行者123 更新时间:2023-12-02 15:30:20 25 4
gpt4 key购买 nike

堆栈溢出,

我想要实现的目标:

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com