我正在尝试在我的网站上构建表格。现在它工作正常:
<table id="objects" class="table">
<thead>
<tr>
<th>#</th>
<th>Object Name</th>
<th>Object Relation Names</th>
<th>Object Relation Types</th>
</tr>
</thead>
<tbody>
@forelse($objects as $object)
<tr>
<td>{{ $object->id }}</td>
<td>{{ $object->name }}</td>
<td>
@foreach($object->relations as $relation)
{{ $relation->name }}
@endforeach
</td>
<td>
@foreach($object->relations as $relation)
{{ $relation->type }}
@endforeach
</td>
</tr>
@empty
<tr>
<td colspan="4" class="text-center">No results.</td>
</tr>
@endforelse
</tbody>
</table>
结果:
--------------------------------------
|#|Name |Relation Name|Relation Type|
--------------------------------------
| | |Relation 1 | 1 |
|1|Name 1|Relation 2 | 2 |
| | |Relation 3 | 1 |
--------------------------------------
| | |Relation 1 | 1 |
|2|Name 2|Relation 2 | 1 |
但我在想是否可以只制作一个foreach循环并在其内部制作。这样的事情:
<table id="objects" class="table">
<thead>
<tr>
<th>#</th>
<th>Object Name</th>
<th>Object Relation Names</th>
<th>Object Relation Types</th>
</tr>
</thead>
<tbody>
@forelse($objects as $object)
<tr>
<td>{{ $object->id }}</td>
<td>{{ $object->name }}</td>
@foreach($object->relations as $relation)
<td>{{ $relation->name }}</td>
<td>{{ $relation->type }}</td>
@endforeach
</tr>
@empty
<tr>
<td colspan="4" class="text-center">No results.</td>
</tr>
@endforelse
</tbody>
</table>
在这种情况下,我得到这样的东西:
--------------------------------------
|#|Name |Relation Name|Relation Type|
--------------------------------------
|1|Name 1|Relation 1 | 1 |Relation 2 | 2 |Relation 3 | 1 |
--------------------------------------
|2|Name 2|Relation 1 | 1 |Relation 2 | 1 |
答案 0 :(得分:0)
你必须做这样的事情
1 @forelse($objects as $object)
2 <tr>
3 <td>{{ $object->id }}</td>
4 <td>{{ $object->name }}</td>
5 @foreach($object->relations as $relation)
6 <td>{{ $relation->name }}</td>
7 <td>{{ $relation->type }}</td>
8 @endforeach
9 </tr>
后行号7添加一个断行标记以避免此问题。
或试试这个。我没有尝试过,因为我不是家。
1 @forelse($objects as $object)
2 @foreach($object->relations as $relation)
3 <tr>
4 <td>{{ $object->id }}</td>
5 <td>{{ $object->name }}</td>
6 <td>{{ $relation->name }}</td>
7 <td>{{ $relation->type }}</td>
8 @endforeach
9 </tr>