How to show has many relation record in Yii2 GridView and DetailView?

Viewed 7212

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

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

Here's my schema code model:

app\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 many hobbies of staff ?

3 Answers

Just get the item data, and after that create a simple yii2 query. For example my 'worker' has city id, with this id we can find city name by this id.

     <?= DetailView::widget([
        'model' => $model,
        'attributes' => [
            'id',
            'name:ntext',
            'surname:ntext',
            'fathers',
            [
                'attribute' => 'city_id',
                'value'=> function($data){
                    $city = City::find()->where(['id'=>$data->city_id])->one();
                    $info = $city->name;
                    return $info;
                },
                'format'=>'html',
            ],
            'status',
            'street',
            'in_company',
        ],
    ]) ?>
Related