Reputation: 6649
Am creating a management system using yii2.
Am trying to display data of many to one relationship but returns an error of not set as shown
Tables:
Case table
Columns: ref_no (primary key),case_description,case_raised_on
Evidence table
Columns: ref_no(foreign key), path, evidence_type
A case can have several evidences and each evidence belongs to a single case
RELATIONSHIPS IN THE MODELS:
Case Model:
public function getEvidences()
{
return $this->hasMany(Evidence::className(), ['case_ref' => 'ref_no']);
}
Evidence model
public function getEvidenceType()
{
return $this->hasOne(EvidenceType::className(), ['type' => 'evidence_type']);
}
The controller
Case controller
public function actionView($id)
{
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
In the view file
<?= DetailView::widget([
'model' => $model,
'attributes' => [
'ref_no',
'case_description',
'raised_on',
'status',
'updated_on',
'evidences.evidence_type',
],
]) ?>
The view file returns an error of not set on the (evidences.evidence_type).It should display the record of all the evidence related to a certain case as referenced by the ref_no2
Upvotes: 4
Views: 1818
Reputation: 5284
Because you are using DetailView Widget of yii2 and it takes only one model. So if you want to get a value from relation you have to call that relation in attribute array:
[
'label' => 'Evidences',
'value' => implode(',',\yii\helpers\ArrayHelper::map($model->evidences, 'id', 'evidence_type')),
],
$model->evidences
is your relation which you have declared in Case Model
Upvotes: 2
Reputation: 4160
You are doing it wrong way since Case Has many Evidences ..
One option is you have to implode array with ,
try,,
<?php
$evidences = \yii\helpers\ArrayHelper::getColumn((\yii\helpers\ArrayHelper::getColumn($model , 'evidences')) ,'evidence_type');
?>
<?= \yii\widgets\DetailView::widget([
'model' => $model,
'attributes' => [
'ref_no',
'case_description',
'raised_on',
'status',
'updated_on',
[
'label' => 'Evidences',
'value' => implode(',' ,$evidences),
],
'evidences.evidence_type',
],
]) ?>
Upvotes: 3