You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Yii2 GridView如何显示外键对应值而非外键ID?

Yii2 GridView显示外键对应国家名称及搜索过滤实现

1. 定义模型关联关系

在models/Customers.php中添加关联方法,建立与Countries模型的关联:

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

该方法通过customers.country_id关联countries.id,用于获取对应国家数据。

2. 修改GridView列配置

替换原有country_id列,改为显示国家名称并添加过滤控件:

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

        'id',
        'email:email',
        'first_name',
        'middle_name',
        'last_name',
        [
            'attribute' => 'country',
            'value' => function ($model) {
                return $model->country ? $model->country->country : '未设置';
            },
            'filter' => \yii\helpers\ArrayHelper::map(\app\models\Countries::find()->all(), 'id', 'country'),
        ],
        [
            'class' => \yii\grid\ActionColumn::className(),
            'urlCreator' => function ($action, \app\models\Customers $model, $key, $index, $column) {
                return \yii\helpers\Url::toRoute([$action, 'id' => $model->id]);
             }
        ],
    ],
]); ?>

注意:需确保已引入yii\helpers\ArrayHelper,若未引入可在文件顶部添加use yii\helpers\ArrayHelper;。

3. 配置搜索模型支持过滤与排序

打开models/SearchCustomers.php,完成以下修改:

3.1 添加搜索属性

在类中新增公共属性:

public $country;

3.2 更新验证规则

在rules()方法中添加:

[['country'], 'safe'],

3.3 修改搜索查询逻辑

在search()方法中关联表并配置排序、过滤条件:

public function search($params)
{
    $query = \app\models\Customers::find();
    // 关联countries表,用于排序和过滤
    $query->joinWith(['country']);

    $dataProvider = new \yii\data\ActiveDataProvider([
        'query' => $query,
        'sort' => [
            'attributes' => [
                'id', 'email', 'first_name', 'middle_name', 'last_name',
                // 配置国家名称的排序
                'country' => [
                    'asc' => ['countries.country' => SORT_ASC],
                    'desc' => ['countries.country' => SORT_DESC],
                ],
            ],
        ],
    ]);

    $this->load($params);

    if (!$this->validate()) {
        return $dataProvider;
    }

    // 原有过滤条件
    $query->andFilterWhere([
        'id' => $this->id,
        'country_id' => $this->country_id,
    ]);

    // 添加国家名称的模糊过滤
    $query->andFilterWhere(['like', 'countries.country', $this->country]);

    return $dataProvider;
}

内容的提问来源于stack exchange,提问作者Raymond

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 12:06:15