首页 > 解决方案 > Laravel 5.3 foreach 来自 2 个不同模型的 2 个集合

问题描述

看法

@foreach ($duplicates as $duplicate)
  <tr>
     <td style="text-align: center;">{{ $duplicate->topic->id }}</td>
     <td style="text-align: center;">{{ $duplicate->topic->title }}</td>
     <td style="text-align: center;">{{ $duplicate->total }}</td>
     @foreach($choices as $choice)
     <td style="text-align: center;">{{ $choice->question_number }}</td>
     <td><a class="btn btn-default" href="choices/{{ $choice->id }}/edit">Шинэчлэх</a></td>
     @endforeach
  </tr>
@endforeach

我想要这样的结果

@foreach ($duplicates as $duplicate)
   <tr>
      <td style="text-align: center;">{{ $duplicate->topic->id }}</td>
      <td style="text-align: center;">{{ $duplicate->topic->title }}</td>
      <td style="text-align: center;">{{ $duplicate->total }}</td>
      <td style="text-align: center;">{{ $choice->question_number }}</td>
      <td><a class="btn btn-default" href="choices/{{ $choice->id }}/edit">Шинэчлэх</a></td>
   </tr>
@endforeach

我想要像 @foreach(duplicates as $duplicate, $choices as $choice) 这样的结果。但我知道我会出错。但如何?

标签: phplaraveleloquent

解决方案


你可以试试

@foreach (array_combine($duplicates->toArray(), $choices->toArray()) as $duplicate => $choice){
    // Do some stuff
@endforeach

如果 Laravel 的刀片语法不允许这样做,那么您总是可以在纯 PHP 中生成 html 并放弃刀片语法。这一切都假设 $duplicates 和 $choices 都是查询对象,从您的代码来看,它们似乎是。


推荐阅读