Yii2, how to use a different model to display in a view file

Sorry for my english. So, I have 3 tables with many relationships.

And this code displaying the attributes in a view file:

    <?= DetailView::widget([
    'model' => $model,
    'attributes' => [
        'scientist_id',
        'scientist_name',
        'scientist_surname',
        'scientist_patronymic',
        'scientist_birthdate',
        'scientist_email:email',
        'scientist_phone',
        'scientist_photo',
        'scientist_status',
        'scientist_job:ntext',
        'scientist_additional_information:ntext',
        'field_id', //display field but no data
    ],
]) ?>

Therefore, I need to display in the field "field_id", which corresponds to the "scientist_id" from the table SUMMARY_FIELD. And how can I do this?

scientific table and others

Relations with tables in the Scientists model:

    public function getSummaryFields()
{
    return $this->hasMany(SummaryField::className(), ['scientist_id' => 'scientist_id']);
}
public function getFields()
{
    return $this->hasMany(Field::className(), ['field_id' => 'field_id'])->viaTable('summary_field', ['scientist_id' => 'scientist_id']);
}

Relations in the SummaryField model:

    public function getField()
{
    return $this->hasOne(Field::className(), ['field_id' => 'field_id']);
}

/**
 * @return \yii\db\ActiveQuery
 */
public function getScientist()
{
    return $this->hasOne(Scientist::className(), ['scientist_id' => 'scientist_id']);
}
+4
source share
1 answer

Create a function in the model:

function getFieldId($model)
{
   $string = '';
   foreach ($model->summaryFields as $cat) {
      $string .= $cat->field_id . " ";
   }
return $string;
}

And access by view Usage $model->functionName():

<?= DetailView::widget([
   'model' => $model,
   'attributes' => [ 
     [
     'attribute'=>'field_id',
     'value' => $model->getFieldId($data),
     ],
   ],
]); ?>
+2
source

Source: https://habr.com/ru/post/1628482/


All Articles