如何在 laravel 中呈现所有相关数据

How to render all data in relation in laravel

我是这种情况下的新手,我不想获得“otmain_many_otline”的价值,但我不知道如何获得它,我想当我使用它时,我应该把它放在数组中 $list->otmain_many_otline[0]->purpose 我只得到第一个数据。我的问题是我不知道如何呈现所有数据的语法?

查看

<table id="example1" class="table table-bordered table-hover">
 <thead>
  <th>Purpose</th>
  </thead>
  <tbody>
  @foreach($ot_list as $list)
   <tr>
    <td>        
       {{$list->otmain_many_otline[0]->purpose}}
    </td>
   </tr>
  @endforeach
  </tbody>
</table>

型号

class OTMain extends Model
{
    protected $table = 'ot_main';
    public function otmain_many_otline(){
        return $this->hasMany('App\OTline', 'ot_main_id','id');
       }

}

class OTLine extends Model
{
    protected $table = 'ot_line';
    public function otline_belong_otmain(){
          return $this->hasOne('App\OTMain', 'ot_main_id');
    }
}

控制器

 $ot_list = OTMain::whereIn('created_by', $requestor_list)
     ->with('otmain_many_otline')
     ->where('ot_status', 1)
     ->get();
 dd($ot_list);

输出:

您的 otmain_many_otline 关系是 hasMany 意味着它将 return 您的相关对象集合。请务必阅读 official documentation on them.

如果您需要获取第一个相关对象,请使用方法first()。在你的情况下:

@foreach($ot_list as $list)
    <tr>
        <td>        
            {{ $list->otmain_many_otline->first()->purpose }}
        </td>
    </tr>
@endforeach

如果您需要渲染所有相关对象,您也可以使用另一个 @foreach:

遍历 omain_many_otline
...
<td>
    @foreach ($list->otmain_many_otline as $otline)
        <p>{{ $otline->purpose }}</p>
    @endforeach
</td>
...

您可以简单地这样做:

@foreach($ot_list as $list)
<tr>
 <td>
    @foreach($list->otmain_many_otline as $ot) // foreach for $otmain_many_otline       
     {{$ot->purpose}} , &nbsp;
    @endforeach
 </td>
</tr>
@endforeach