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

kd3sttzy  于 12个月前  发布在  其他
关注(0)|答案(2)|浏览(220)

很新的yii,我的问题是类似于这个问题How to get foreign key value instead of key in grid view with searching and filtering in yii 2?
我也看过这个wiki https://www.yiiframework.com/wiki/621/filter-sort-by-calculatedrelated-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


的数据

kyxcudwk

kyxcudwk1#

你必须使用$model示例来获取$model值(我假设你在Customer模型中定义了这个,在Country模型中定义了revers方法,也希望你在创建表时也有FK):Customer

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 
    },
]

z4bn682m

z4bn682m2#

更原生的方式是通过点分隔符指定relation.attribute。标签和其他数据将从关系中自动检索。
假设你已经有了模型的关系country

GridView::widget([
        // ...
        'columns' => [
            // Example 1. Just get label and value `as is` from relation
            'country.country'

            // Example 2. If you want custom output or label
            [
                'attribute' => 'country.country',
                'format' => 'html',
                'value' => function (Country $model) {
                    return '#' . $model->id . ' <strong>' . $model->country . '</strong>';
                },
            ],
        ],
    ]);

字符串

相关问题