yii2 - YII2模型关系输出gridview
问题描述
我在 yii2 模型中有以下关系:
public function getJobInfos()
{
return $this->hasMany(JobInfo::className(), ['ID' => 'ID']);
}
Tbl JobInfo:
CREATE TABLE [dbo].[JobInfo](
[ID] [uniqueidentifier] ROWGUIDCOL NOT NULL,
[Parameter] [int] NULL,
[Value] [varchar](255) NULL,
....
在 GridView 中访问 JobInfo有效:
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'ID',
[
'label' => 'Strings',
'value' => function ($data) {
$strings = [];
foreach($data->jobInfos as $JobInfo) {
$strings[] = $JobInfo->Value;
}
return implode(',', $strings);
},
],
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
现在 JobInfo 中的所有内容都加载到字符串列中。
现在如何为一组选择新列:$JobInfo->Parameter (Label) 和 $JobInfo->Value (Value)?例如,如果参数是“OrderNo”?
不幸的是,使用 Foreach 创建列不起作用。
谢谢!
解决方案
使用类似的东西:
索引.php
[
'class' => 'kartik\grid\ExpandRowColumn',
'width' => '300px',
'value' => function ($model, $key, $index, $column) {
return GridView::ROW_COLLAPSED;
},
'detail' => function ($model, $key, $index, $column) {
return Yii::$app->controller->renderPartial('_expandableview', ['model' =>
$model]);
},
'disabled'=> function ($model, $key, $index, $column) {
$rows = $model->jobInfos;
if (!empty($rows)) { return false;} else { return true;}
},
'headerOptions' => ['class' => 'kartik-sheet-style'],
'expandOneOnly' => true,
],
可扩展视图:
<div class="Info-expandable-view">
<table border="0" class="table transparent">
<?php
$rows = $model->jobInfos;
foreach ($rows as $key => $value) {
//split your columns here using
//$myParameter = $value['Parameter'];
//$myValue = $value['Value'];
}