Search code examples
phpgridviewyii2yii2-advanced-appyii2-basic-app

How to fetch the result from multiple tables to gridview?


Question: Let's Say i have two tables,

Table1            Table2
-authorId         -username
-moderatorId      -id

As of now my view looks like this,

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

Expected Result I would like to display author name of every post in gridview, I tried using authorId but it displays only id of the author. How should i use the "authorId" column to map to "username" column.

Thanks in Advance,


Solution

  • In you Table1 related Model add two Active Relation (one for Author and One Moderator ) for retrive the related names

    Setup Table1 model

    /* 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']);
        }
    

    then build two getter one for Author name and one for Moderator name

    /* Getter for author name */
    public function getAuthorName() {
            return $this->author->username;
    }
    
    /* Getter for moderator name */
    public function getModeratorName() {
            return $this->moderator->username;
    }
    

    add your model attribute labels

        /* Your model attribute labels */
    public function attributeLabels() {
            return [
                /* Your other attribute labels */
                'AuthorName' => Yii::t('app', 'Author Name'),
                'ModeratorName' => Yii::t('app', 'Moderator Name')
            ];
    }
    

    then your gridView you can user the new getters

    'columns' => [
            ['class' => 'yii\grid\SerialColumn'],
                ....
            ....
            'authorName',
            'moderatorName',
            ['class' => 'yii\grid\ActionColumn'],
        ],