如何在 yii 2 的网格视图中显示外键值而不是键?

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

对 yii 很新,我的问题与这个问题类似如何在 yii 2 中通过搜索和过滤获取外键值而不是网格视图中的键?

我也看过这个wiki https://www.yiiframework.com/wiki/621/filter-sort-by-calculatedlated-fields-in-gridview-yii-2-0#hh10

我无法弄清楚上面的回复中的代码在哪里。

我有以下表格

CREATE TABLE `customers` (
  `customer_id` int(10) NOT NULL,
  `email` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
  `first_name` varchar(255) DEFAULT NULL,
  `middle_name` varchar(255) DEFAULT NULL,
  `last_name` varchar(255) DEFAULT NULL,
  `country_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

country_id
是外键。

CREATE TABLE `countries` (
  `id` int(11) NOT NULL,
  `country` varchar(45) NOT NULL,
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

网格视图

<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => [
        ['class' => 'yii\grid\SerialColumn'],

        'id',
        'email:email',
        'first_name',
        'middle_name',
        'last_name',
        'country_id',
        [
            'class' => ActionColumn::className(),
            'urlCreator' => function ($action, Customers $model, $key, $index, $column) {
                return Url::toRoute([$action, 'id' => $model->id]);
             }
        ],
    ],
]); ?>

我可以在网格视图中显示国家/地区的

id
。如何显示
country
而不是
id

php gridview yii yii2
1个回答
0
投票

你必须使用 $model 实例来获取 $model 值:

public function getCountry()
{
   return $this->hasOne(Country::class, ['id' => 'country_id]);
}

然后在网格视图中:

...
[
    'attribute' => 'country_id',
    'label' => 'Country',
    'value' => function(Customer $model){
       return $model->country->country; // I'm surprised that for the field name you used the same field name as a model, it will be better NAME because it more relevant here 
    },
]
© www.soinside.com 2019 - 2024. All rights reserved.