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

kd3sttzy  于 2024-01-09  发布在  其他
关注(0)|答案(2)|浏览(295)

很新的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
我无法弄清楚什么代码在上面的回复中的位置。
我有以下表格

  1. CREATE TABLE `customers` (
  2. `customer_id` int(10) NOT NULL,
  3. `email` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
  4. `first_name` varchar(255) DEFAULT NULL,
  5. `middle_name` varchar(255) DEFAULT NULL,
  6. `last_name` varchar(255) DEFAULT NULL,
  7. `country_id` int(11) NOT NULL
  8. ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

字符串
country_id是外键。

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

网格视图

  1. <?= GridView::widget([
  2. 'dataProvider' => $dataProvider,
  3. 'filterModel' => $searchModel,
  4. 'columns' => [
  5. ['class' => 'yii\grid\SerialColumn'],
  6. 'id',
  7. 'email:email',
  8. 'first_name',
  9. 'middle_name',
  10. 'last_name',
  11. 'country_id',
  12. [
  13. 'class' => ActionColumn::className(),
  14. 'urlCreator' => function ($action, Customers $model, $key, $index, $column) {
  15. return Url::toRoute([$action, 'id' => $model->id]);
  16. }
  17. ],
  18. ],
  19. ]); ?>


我可以在网格视图中显示国家的id。如何显示country而不是id


的数据

kyxcudwk

kyxcudwk1#

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

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

字符串
然后在网格视图中:

  1. ...
  2. [
  3. 'attribute' => 'country_id',
  4. 'label' => 'Country',
  5. 'value' => function(Customer $model){
  6. 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
  7. },
  8. ]

展开查看全部
z4bn682m

z4bn682m2#

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

  1. GridView::widget([
  2. // ...
  3. 'columns' => [
  4. // Example 1. Just get label and value `as is` from relation
  5. 'country.country'
  6. // Example 2. If you want custom output or label
  7. [
  8. 'attribute' => 'country.country',
  9. 'format' => 'html',
  10. 'value' => function (Country $model) {
  11. return '#' . $model->id . ' <strong>' . $model->country . '</strong>';
  12. },
  13. ],
  14. ],
  15. ]);

字符串

展开查看全部

相关问题