如何在Yii2 GridView和DetailView中显示有很多关系记录?

时间:2016-03-25 15:28:47

标签: php gridview yii2 detailview

我希望工作人员在详细视图和gridview中有很多兴趣爱好。

但我收到错误异常Trying to get property of non-object

这是我的架构代码模型:

  

应用\模型\ TblDataStaff

enter image description here

    ....
        public function getTblDataHobis()
            {
                return $this->hasMany(TblDataHobies::className(), ['id_staff' => 'id']);
            }
  

查看代码:查看。

<?= DetailView::widget([
        'model' => $model,
        'attributes' => [
...
['attribute'=>'namHob','value'=>$model->tblDataHobis->id],
...
],
    ]) ?>
  

指数:

<?= GridView::widget([
        'dataProvider' => $dataProvider,
        //'filterModel' => $searchModel,
        'columns' => [
            ['class' => 'yii\grid\SerialColumn'],
......
['attribute'=>'namHob','value'=>function($namHob){return $namHob->tblDataHobis->name_hobby;},],
.....
['class' => 'yii\grid\ActionColumn'],
        ],]);?>

如何展示很多员工的爱好?

2 个答案:

答案 0 :(得分:7)

没什么奇怪的,因为Trying to get property of non-object会返回$model->tblDataHobisTblDataHobies对象数组而导致 // display hobbies names separated with commas echo implode(', ', \yii\helpers\ArrayHelper::map($model->tblDataHobis, 'id', 'name_hobby')); 错误。

你可以试试这个:

DetailView

'value' => implode(\yii\helpers\ArrayHelper::map($model->tblDataHobis, 'id', 'name_hobby')),

GridView

'value' => function($model) { return implode(\yii\helpers\ArrayHelper::map($model->tblDataHobis, 'id', 'name_hobby')), },

201

答案 1 :(得分:0)

尝试:

<?= DetailView::widget([
        'model' => $model,
        'attributes' => [

         [
              'header' => 'number of hobbies',
              'value' => function($data) {
                       return $data->getTblDataHobis()->count();
              }
          ]

    ]) ?>