An Pham Karion Co.Ltd
An Pham Karion Co.Ltd

Reputation: 461

Relational data fields display in Yii2 Details views

I have a Table KHDN references table Loaihinh via foreign key loaihinh_ten

Table Loaihinh:

Table KHDN:

What should i do if i want to show Loaihinh. loai instead of the foreign key loaihinh_ten in khdn/views.php Yii2:

<?php

use yii\widgets\DetailView;

/* @var $this yii\web\View */
/* @var $model common\models\Khdn */
?>
<div class="khdn-view">

    <?= DetailView::widget([
        'model' => $model,
        'attributes' => [
            'id',
            'ten:ntext',
            'chudautu:ntext',
            'ngaybatdau:ntext',
            'ngayhoanthanh:ntext',
            'giatri:ntext',
            'trangthai_ten',
            'diachi:ntext',
            'ghichu:ntext',
            'loaihinh_ten',
        ],
    ]) ?>

</div>

thanks you so much!!

Upvotes: 2

Views: 1429

Answers (2)

bipin panday
bipin panday

Reputation: 119

There are many method of doing this things. you can use any of the following methods for this problem.

you need not to use joinWith method for this you can get that relation data any where in your program just using

$model->relation_name_decleared_in_model

below is the sample code that is use a

 <?= GridView::widget([
    'dataProvider' => $dataProvider,
    //'filterModel' => $searchModel,
    'columns' => [
        ['class' => 'yii\grid\SerialColumn'],
        [
            'attribute' => 'type',
            'value' => function ($model) {
                return  \app\models\BlockType::getConstantMessage($model->type);
            },
        ],
        [
            'class' => 'kartik\grid\EditableColumn',
            'header' => 'POSITION',
            'attribute' => 'position',
        ],
        [
            'attribute' => 'access',
            'value' => function ($model) {
                return  \app\components\Helper::ACCESS[$model->access];
            },
        ],
        'some_attribute',
        [
           'attribute' => 'other_relation',
           'value' => 'model.relation.column'
         ],
        [
            'attribute' => 'Page',
            'value' => function ($model) {
                return  $model->page->pageContent->name;
            },
        ],

        ['class' => 'yii\grid\ActionColumn'],
    ],
]); ?>

Upvotes: 2

Pratik Karmakar
Pratik Karmakar

Reputation: 257

Use

$model->relationName->fieldName

Example:

 /**
 * @return \yii\db\ActiveQuery
 */
 public function getLoaihinh()
{
    return $this->hasOne(KHDN::className(), ['id' => 
      'loaihinh_ten']);
}

Then use the following relation in View:

 $model->loaihinh->loai;

Upvotes: 2

Related Questions