2016-10-26 31 views
1

在index.php中列上合併基於關係表中的GridView yii2

'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' 
     ], 

這是iDKARYAWAN是從另一個表的關係在我的模型

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

create方法相關模型叫getFullName()和使用PHP級聯計算全名:

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

然後在GridView的是:

use yii\helpers\Html; 

... 

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

attributeLabels()方法相關模型可選爲它定義一個標籤可能在一列中顯示相關模型的全名,如下所示:

1)最短形式:

'relatedModel.fullName', 

2)重寫標籤:

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

3)使用閉合:

[ 
    '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; 
    }, 
], 

的另一種方法是計算滿名稱使用SQL,並作爲查詢結果的一部分包含在單獨的列中。

使用Active Record - Selecting extra fields官方文檔部分作爲指南,也可以在Github上看到這個相關問題 - JoinWith - assign a column aliases to an attribute of related model

$fullName添加爲相關模型類的公共屬性。修改查詢像這樣:

use yii\db\Expression; 

... 

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

然後在GridView欄顯示它您可以使用上述desribed一個選項,例如:

'relatedModel.fullName'