Yii2 how to get relations and get id header using foreign key

I have an event model and one event has one project, from one to one association, and I have a recording function in the event model to get the project below

 public function getprojects() {
    return $this->hasOne(app\models\Project::className(), ['id' => 'projectid']);
}

and below is the code of my controller

if ($model->load(Yii::$app->request->post()) && $model->save()) {
            $project = $model->project;
            return $this->redirect(['eventdetail', 'id' => $model->id, 'project' => $project]);
        }

and detailed view code

 <?= DetailView::widget([
        'model' => $model,
        'attributes' => [
            'id',
            'projectid',
            'userid',
            'milestone',
            'datetime',
        ],
    ]) ?>

I want to print the Title project instead of projectid, and we will get the title from the linked table, how do I get the title and print in the detail view

+4
source share
2 answers

1) The easiest way if you only need a text value is to change projectIdto projects.title:

'attributes' => [
    'projects.title',
],

In addition, the label will be taken from the model Projects.

2) .

:

'attributes' => [
    [        
        'attribute' => 'avatar',
        'format' => 'raw',
        'value' => $model->getAvatar(),
    ],
],
+3

DetaileView, magic methods.

<?= DetailView::widget([
        'model' => $model,
        'attributes' => [
            'id',
             array(
                'attribute' => 'projectid',
                'value' => $model->project->title,
            )
            'userid',
            'milestone',
            'datetime',
        ],
    ]) ?>

:

, namespace

use app\models\Project;

-, , camelcase getProject, getProjects - .

 public function getProject() {
    return $this->hasOne(Project::className(), ['id' => 'projectid']);
}
0

All Articles