代码之家  ›  专栏  ›  技术社区  ›  5.1tat

如何将多个表的结果提取到gridview?

  •  0
  • 5.1tat  · 技术社区  · 7 年前

    问题: 假设我有两张桌子,

    Table1            Table2
    -authorId         -username
    -moderatorId      -id
    

    现在我的观点是这样的,

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

    预期结果 我想在gridview中显示每篇文章的作者姓名, 我尝试使用authorId,但它只显示作者的id。 如何使用“authorId”列映射到“username”列。

    提前感谢,

    1 回复  |  直到 7 年前
        1
  •  2
  •   ScaisEdge    7 年前

    在Table1相关模型中,添加两个活动关系(一个用于作者,一个用于版主),以检索相关名称

    设置表1模型

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