如何从多个表中获取结果到gridview?

问题描述 投票:0回答:1

问题:我们说我有两张桌子,

Table1            Table2
-authorId         -username
-moderatorId      -id

截至目前,我的观点看起来像这样,

[    
              'label' => 'Author', 
              'value' => function($something){
                    return $something->transaction->authorId ?? null; 
              },
              'attribute' => 'author'
],

预期结果我想在gridview中显示每个帖子的作者姓名,我尝试使用authorId,但它只显示作者的id。我应该如何使用“authorId”列映射到“用户名”列。

提前致谢,

php gridview yii2 yii2-advanced-app yii2-basic-app
1个回答
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,为Moderator名称构建一个

/* 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'],
    ],
© www.soinside.com 2019 - 2024. All rights reserved.