How to show many relationship records in Yii2 GridView and DetailView?

I want to show that the staff has many hobbies from table hobbies in the detail view and gridview.

But I got an error exception Trying to get property of non-object

Here is my schema code model:

Application \ Model \ TblDataStaff

enter image description here

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

view code: view.

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

index:

<?= 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'],
        ],]);?>

How to show a lot of staff hobbies?

+4
source share
2 answers

Nothing strange, you have an error Trying to get property of non-objectsimply because it $model->tblDataHobisreturns an array of objects TblDataHobies.

You can simply try the following:

// display hobbies names separated with commas
echo implode(', ', \yii\helpers\ArrayHelper::map($model->tblDataHobis, 'id', 'name_hobby'));

For DetailView:

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

For GridView:

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

Try:

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

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

    ]) ?>
0
source

All Articles