我希望工作人员在详细视图和gridview中有很多兴趣爱好。
但我收到错误异常Trying to get property of non-object
这是我的架构代码模型:
应用\模型\ TblDataStaff
....
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'],
],]);?>
如何展示很多员工的爱好?
答案 0 :(得分:7)
没什么奇怪的,因为Trying to get property of non-object
会返回$model->tblDataHobis
个TblDataHobies
对象数组而导致 // 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();
}
]
]) ?>