【问题标题】:How to fetch the result from multiple tables to gridview?如何从多个表中获取结果到gridview?
【发布时间】:2018-01-23 07:46:26
【问题描述】:

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

Table1            Table2
-authorId         -username
-moderatorId      -id

目前我的看法是这样的,

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

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

提前致谢,

【问题讨论】:

  • 也许关系就是你要找的yiiframework.com/doc-2.0/…
  • 如果您在上述表中的数据库中有外键,您可以通过 gii 在模型中轻松生成关系,然后在视图中简单地使用它们(参见上面的链接)。

标签: php gridview yii2 yii2-advanced-app yii2-basic-app


【解决方案1】:

在您的 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'],
    ],

【讨论】:

  • 它成功了,谢谢队友 :) 我怎样才能在 gridview 上使用搜索框?有什么想法吗?
  • 你可以看看yiiframework.com/wiki/621/… .. 在场景 2 中,您可以找到 seacrh 和排序相关列的方式.. 如果我的回答是正确的,请将其标记为已接受,请参阅此处@ 987654322@
  • 您好,如果您能帮助我解决我现在面临的问题,那就太好了,添加的更新在一个 gridview 页面中可以正常工作。但是还有另一个 gridview 页面首先扩展了这个模型,我得到“获取未知属性:app\models\Transactions::authorName”
  • 你应该发布一个新问题..用相关代码清楚地描述..
猜你喜欢
  • 2017-11-12
  • 2013-06-26
  • 2011-12-08
  • 1970-01-01
  • 2011-12-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多