在gridview Yii 2中显示另一个表的字段

时间:2015-12-15 01:12:15

标签: php gridview yii2

我有一个名为hosts的表,另一个是hostgroup。在我的主机表上,它包含以下字段:id,name和hostgroup_id。在我的hostgroup表格中,其字段为idname。我希望在主机表格的view/index.php上显示idname,并根据其hostgroup.name显示主机组表id Also, do you have any idea how I can make it redirect to the更新了某个ID的page of hostgroup`?

在我的main_directory/model/HostsSearch.php我有这个:

public function getHostgroup()
{
    return $this->hasOne(HostgroupsSearch::className(), ['id' => 'parent_host_id']);
}

在我的main_dir/view/hosts/index.php下,我有这个:

  <?=
  GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'columns' => [
            'id',
            'name',
            'parent_host_id.name',
            [
                'label' => 'Name',
                'value' => 'HostgroupsSearch.name',
            ],
            'ip_address',
            'object_name',
        ],
    ?>  

1 个答案:

答案 0 :(得分:2)

main_directory/model/Hosts.php模型文件

中添加此功能
public function getHostgroup()
{
    return $this->hasOne(HostgroupsSearch::className(), ['id' => 'parent_host_id']);
}

网格视图:

<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => [
        'id',
        'name',
        'parent_host_id.name',
        [
            'label' => 'Name',
            'value' => 'hostgroup.name',
        ],
        'ip_address',
        'object_name',
    ],
?>