Yii2新手求助:Bootstrap表格如何显示关联表Car的state_num
问题:Yii2中用普通Bootstrap表格显示关联表字段(car.state_num)
作为Yii2新手,我之前用GridView能正常展示Contract表关联的Car和Driver数据,其中Car列显示的是car.state_num;但换成普通Bootstrap表格后,只能显示car_id,想知道怎么修改才能显示车辆的状态编号(state_num)。
原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', ['class' => 'yii\grid\ActionColumn'], ], ]);
当前的Bootstrap表格代码(仅显示car_id):
<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>
解决方案
其实原理和GridView的写法是一致的,Yii2的ActiveRecord支持通过关联关系直接调用关联模型的字段,只需要两步就能搞定:
确认Contract模型已定义关联关系
既然你之前用GridView能正常显示,那你的Contract模型里应该已经有了和Car表的关联方法,大概是这样的:// 在models/Contract.php中 public function getCar() { return $this->hasOne(Car::className(), ['id' => 'car_id']); }如果没有的话,先补上这段代码,这是关联查询的基础。
修改Bootstrap表格的Car列代码
把原来显示car_id的代码,改成直接调用关联模型的state_num字段:<td><?= $item->car->state_num ?></td>不过为了避免出现关联车辆不存在时的报错,建议加上空值判断,让代码更健壮:
<td><?= $item->car ? $item->car->state_num : '无关联车辆' ?></td>
修改后的完整表格代码
<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 ? $item->car->state_num : '无关联车辆' ?></td> <td><?= $item->first_date ?></td> <td><?= $item->second_date ?></td> <td><?= $item->status ?></td> </tr> <? endforeach; ?> </tbody> </table>
性能优化小提示
如果数据量比较大,可以在控制器的dataProvider里提前预加载关联数据,避免循环里的N+1查询问题,比如在控制器中:
$dataProvider->query->with('car');
这样就能一次性把所有Contract关联的Car数据查出来,提升页面加载速度。
内容的提问来源于stack exchange,提问作者Andreykin Sergey
相关产品推荐
相关产品推荐

