我是Yii2中的新手而且我没有尝试在视图中显示数据。我之前就这样做了(使用GridView):
GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
[
'attribute' => 'car_id',
'value' => 'car.state_num'
],
[
'attribute' => 'driver_id',
'value' => 'driver.name'
],
'status',
'first_date',
'second_date',
// 'status',
// 'foto:ntext',
// 'description:ntext',
['class' => 'yii\grid\ActionColumn'],
],
]);
(它的视图显示'合约'表,其中包含'Driver'和'Car'表格)
但是现在我想通过常见的引导表来做,像这样:
<table class="table table-striped">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Car</th>
<th scope="col">Start</th>
<th scope="col">Finish</th>
<th scope="col">Status</th>
</tr>
</thead>
<tbody>
<?php foreach ($dataProvider->getModels() as $item):?>
<tr>
<th scope="row">Order ID <?= $item->id ?> </th>
<td><?= $item->car_id ?></td>
<td><?= $item->first_date ?></td>
<td><?= $item->second_date ?></td>
<td><?= $item->status ?></td>
</tr>
<? endforeach; ?>
</tbody>
</table>
它也有效,但Car的专栏显示了car_id .. 问题:如何在视图中显示car.state_num?
答案 0 :(得分:1)
使用$item->car->state_num
:
<table class="table table-striped">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Car</th>
<th scope="col">Start</th>
<th scope="col">Finish</th>
<th scope="col">Status</th>
</tr>
</thead>
<tbody>
<?php foreach ($dataProvider->getModels() as $item):?>
<tr>
<th scope="row">Order ID <?= $item->id ?> </th>
<td><?= (!empty($item->car_id)) ? $item->car->state_num : null ?></td>
<td><?= $item->first_date ?></td>
<td><?= $item->second_date ?></td>
<td><?= $item->status ?></td>
</tr>
<? endforeach; ?>
</tbody>
</table>