问题: 我们说我有两张桌子,
Table1 Table2
-authorId -username
-moderatorId -id
截至目前,我的观点看起来像这样,
[
'label' => 'Author',
'value' => function($something){
return $something->transaction->authorId ?? null;
},
'attribute' => 'author'
],
预期结果 我想在gridview中显示每个帖子的作者姓名, 我尝试使用authorId但它只显示作者的id。 我应该如何使用“authorId”列映射到“用户名”列。
先谢谢,
答案 0 :(得分:2)
在Table1相关模型中添加两个Active Relation(一个用于Author和一个Moderator)以检索相关名称
设置Table1模型
/* ActiveRelation for Author*/
public function getAuthor()
{
return $this->hasOne(Table2Model::className(), ['id' => 'author_id']);
}
/* ActiveRelation for Moderator */
public function getModerator ()
{
return $this->hasOne(Table2Model::className(), ['id' => 'moderator_id']);
}
然后为作者姓名构建两个getter,为主持人名称
构建一个/* Getter for author name */
public function getAuthorName() {
return $this->author->username;
}
/* Getter for moderator name */
public function getModeratorName() {
return $this->moderator->username;
}
添加模型属性标签
/* Your model attribute labels */
public function attributeLabels() {
return [
/* Your other attribute labels */
'AuthorName' => Yii::t('app', 'Author Name'),
'ModeratorName' => Yii::t('app', 'Moderator Name')
];
}
然后你的gridView你可以使用新的getter
'columns' => [
['class' => 'yii\grid\SerialColumn'],
....
....
'authorName',
'moderatorName',
['class' => 'yii\grid\ActionColumn'],
],