yii2 - 如何在 yii2 中连接 3 个表并在 Gridview 中显示然后使排序正常工作

标签 yii2

我已经使用 gii 工具来创建 crud 应用程序。我有 3 个表,即 tbl_targetcities、lib_cities 和 lib_provinces。我能够将 lib_cities 连接到 tbl_targetciteis,但不能连接到 lib_provinces。而且城市/自治市的分类也不起作用。似乎它是根据 ID 排序的。

tbl_target_cities

enter image description here

lib_cities

enter image description here

lib_provinces

enter image description here

sample View

enter image description here

到目前为止,这是我在模型中的关系。

public function getCityName()
{
  return $this->hasOne(LibCities::className(),['city_code'=>'city_code']);
}

在我的 View 文件中...
    <?= GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => [
        ['class' => 'yii\grid\SerialColumn'],
        [
            'attribute'=>'city_code',
            'value'=>'cityName.city_name'
        ],
                   [
            'attribute'=>'prov code',
            'value'=>'cityName.city_name'
        ],
        'kc_classification',
        'cluster',
        'grouping',
         'priority',
        'launch_year',

        ['class' => 'yii\grid\ActionColumn'],
    ],
]); ?>

如何显示来自 lib_provinces 的 prov_name ???

编辑以在评论框中回答 user2839376 问题

在搜索模型类中
$query = TblSpBub::find();
    $query->joinWith('brgyCode')->joinWith(['cityCode'])->joinWith(['cityCode.provCode']);

    $covered=  LibAreas::find()->where(['user_id'=>yii::$app->user->identity->id])->all();

    $query->all();

    $dataProvider = new ActiveDataProvider([
        'query' => $query,
        'sort'=> ['defaultOrder' => ['id'=>SORT_DESC]],
    ]);

    $dataProvider->sort->attributes['city'] = [
    'asc' => ['lib_Cities.city_name' => SORT_ASC],
    'desc' => ['lib_Cities.city_name' => SORT_DESC],
    ];

    $dataProvider->sort->attributes['province'] = [
    'asc' => ['lib_provinces.prov_name' => SORT_ASC],
    'desc' => ['lib_provinces.prov_name' => SORT_DESC],
    ];

最佳答案

LibCities模型添加新关系:

public function getProvince()
{
  return $this->hasOne(LibProvince::className(),['prov_code'=>'prov_code']);
}

并更改getCityName关系。您应该添加 with()对于关系:
public function getCityName()
{
  return $this->hasOne(LibCities::className(),['city_code'=>'city_code'])->with(['province']);
}

并考虑将您的专栏更正为:
 [
            'attribute'=>'prov code',
            'value'=>'cityName.province.prov_name'
        ],

关于yii2 - 如何在 yii2 中连接 3 个表并在 Gridview 中显示然后使排序正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29505137/

相关文章:

php - 从复选框列表 yii2 中获取值

yii2 - 如何在 Yii2 中禁用 Assets 缓存?

php - 使用 Yii2 扩展通过 swiftmailer 发送电子邮件

php - 关于Yii2 RBAC的疑惑

mysql - yii2 中的多个 where 条件

gridview - Yii2 gridview 过滤器使用自动完成文本框

php - yii2 在查询中选择 NULL 值(选择 NULL 作为列,...)

php - 如何禁用updated_at的时间戳值?

YII2 Kartik gridview禁用pdf导出

javascript - "submit"JavaScript/jQuery 之后