2016-10-26 10 views
1

をマージ:iDKARYAWANあるは、GridViewのyii2に列ベースのリレーショナルテーブルの上のindex.phpで

'columns' => [ 
    ['class' => 'yii\grid\SerialColumn'], 
     'ID_REQUEST', 
     'NOMOR_SURAT', 
     [ 
      'label' => 'Nama Depan',  
      'attribute' => 'ID_KARYAWAN', 
      'value' => 'iDKARYAWAN.FIRST_NAME' 
     ], 
     [ 
      'label' => 'Nama Belakang', 
      'attribute' => 'ID_KARYAWAN', 
      'value' => 'iDKARYAWAN.LAST_NAME' 
     ], 

は、これらの2つの列をマージするためにどのようにモデル内の別のテーブルからリレーション

class Request extends \yii\db\ActiveRecord { 

/** 
* @inheritdoc 
*/ 
public static function tableName() { 
    return 'ytms_it.request'; 
} 

public function getIDKARYAWAN() { 
    return $this->hasOne(Karyawan::className(), ['ID_KARYAWAN' => 'ID_KARYAWAN'])->from(Karyawan::tableName(). ' b'); 
} 

のですか?

elpの場合は、ありがとうございます。

答えて

1

メソッドを作成しますが、関連するモデルでgetFullName()と呼ばれるPHPの連結を使用して完全な名前を計算する:

use yii\helpers\Html; 

... 

/** 
* @return string 
*/ 
public function getFullName() 
{ 
    return Html::encode($this->name . ' ' . $this->surname); 
} 

は、必要に応じて、関連するモデルのattributeLabels()方法でそれのためのラベルを定義します。

`fullName` => 'Label for full name', 

その後のGridViewで、それはです関連するモデルのフルネームを1列に表示することができます。

1)最短形式:

[ 
    'attribute' => 'relatedModel.fullName', // The attribute name can be different in this case 
    'value' => function ($model) { 
     // You can calculate full name here. 
     // But it's better to just call according method since view is only for display. 
     return $model->author->fullName; 
    }, 
], 

別の方法は、完全計算することである:クロージャを使用

[ 
    'attribute' => 'relatedModel.fullName', 
    'label' => 'Overrided label', 
], 

3)

'relatedModel.fullName', 

2)ラベルをオーバーライドSQLを使用して名前を付け、クエリ結果の一部として別の列に追加します。

Active Record - Selecting extra fields公式ドキュメントのセクションを参考にして、Github - JoinWith - assign a column aliases to an attribute of related modelに関するこの関連の問題も参照してください。

$fullNameを関連モデルクラスのパブリックプロパティとして追加します。あなたは、たとえば、上記desribedのいずれかのオプションを使用することができますGridView列に表示しその後

use yii\db\Expression; 

... 

->joinWith(['relatedModel' => function (\yii\db\ActiveQuery $query) { 
    $query->addSelect('fullName' => new Expression("CONCAT(name, ' ', surname)")]); 
}] 

:そうのようにクエリを変更し

'relatedModel.fullName' 
関連する問題