Yii2 如何在网格视图中锚定关系的值


Yii2 how to anchor the value of the relationship in the GridView

我是初学者。我解释这个话题:

Ticket模型中存在这种关系:

public function getTyp()
{
    return $this->hasOne(Typology::className(), [ 'id' =>'typ_id']);
}

在工单表中有typ_id列(它与类型表的 id 相关)。在views/ticket/index.php的观点中,这些columns GridView::widget

  [
     'attribute' => 'typ_id',
     'value' => 'typ.typology' 
  ],

我想锚定关系的价值。我试过这个:

  [
     'attribute' => 'typ_id',
     'value' => function ($model) {
               return Html::a (
              'typ.typology',
              '/typology/view?id='.$model->typ_id
               );
      }
  ]

但它不起作用

有人可以帮助我吗?

Html::a() 将typ.typology解释为原始字符串。在值闭包中使用$model通过关系获取必要的属性。

此外,不要手动连接 url 及其参数,只需将它们传递到数组中(请参阅 Url::to() 以了解链接是如何构造的)。

[
    'attribute' => 'typ_id',
    'value' => function ($model) {
        return Html::a($model->typ->typology, ['/typology/view', 'id' => $model->typ_id]);
    },
],