Laravel 5.3 foreach 2 个不同型号的 2 个集合



>View

@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这样的结果(重复为 $duplicate,$choices为 $choice(。 但我知道我会出错。 但是怎么做呢?

你可以试试

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

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

你试过使用Eloquent:Relations吗? 我这里没有 pc,所以我没有生成一个示例来测试它,但我希望它会有所帮助。

拉拉维尔雄辩的关系文档

最新更新