yii2 在 gridview 中从关系中添加列并在 gridview 中排序

yii2 adding column in the gridview from relation and sorting in gridview

我有两个问题...

我有3张桌子。 tbl_target_cities、lib_cities 和 lib_provinces。

通过学习视频教程,我能够将数据从 tbl_target_cities 显示到 gridview,并将其连接到 lib_cities。

除了来自关系的 CITY/MUNICIPALITY 列外,gridview 中的排序工作完美。

问题1:如何更正CITY/MUNICIPALITY列的排序?

问题2:如何添加带有搜索框和排序功能的省份列?

tbl_target_cities

+-------------------+-----------------------+
| Field             | Type                  |
+-------------------+-----------------------+
| id                | int(11)               |
| city_code         | varchar(20)           |
| kc_classification | varchar(100)          |
| cluster           | enum('1','2','3','4') |
| grouping          | int(11)               |
| priority          | varchar(100)          |
| launch_year       | int(11)               |
+-------------------+-----------------------+

lib_cities

+---------------+--------------+------+-----+---------+-------+
| Field         | Type         | Null | Key | Default | Extra |
+---------------+--------------+------+-----+---------+-------+
| city_code     | char(9)      | NO   | PRI |         |       |
| city_name     | varchar(100) | NO   | MUL | NULL    |       |
| prov_code     | char(9)      | NO   | MUL | NULL    |       |
| is_Urban      | tinyint(1)   | YES  |     | 0       |       |
| locked        | tinyint(1)   | YES  |     | 0       |       |
| app_target_hh | int(5)       | YES  |     | NULL    |       |
| 4p_areas      | tinyint(1)   | NO   |     | NULL    |       |
+---------------+--------------+------+-----+---------+-------+

lib_provinces

+-------------+-------------+------+-----+---------+-------+
| Field       | Type        | Null | Key | Default | Extra |
+-------------+-------------+------+-----+---------+-------+
| prov_code   | char(9)     | NO   | PRI |         |       |
| prov_name   | varchar(60) | NO   | MUL | NULL    |       |
| region_code | char(9)     | NO   | MUL | NULL    |       |
+-------------+-------------+------+-----+---------+-------+

TblTargetCities 模型

<?php

namespace backend\models;

use Yii;

/**
 * This is the model class for table "tbl_target_cities".
 *
 * @property integer $id
 * @property string $city_code
 * @property string $kc_classification
 * @property string $cluster
 * @property integer $grouping
 * @property string $priority
 * @property integer $launch_year
 */
class TblTargetCities extends \yii\db\ActiveRecord
{

    public $province;
    public $region;

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'tbl_target_cities';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['region', 'kc_classification', 'cluster', 'grouping', 'priority', 'launch_year'], 'required'],
            [['cluster','province','region'], 'string'],
            [['grouping', 'launch_year'], 'integer'],
            [['city_code'], 'string', 'max' => 20],
            [['city_code'], 'required', 'message' => 'Please select a city or municipality.'],
            [['kc_classification', 'priority'], 'string', 'max' => 100],
            [['city_code'], 'unique','message'=>'City/Municipality is already covered.'],
            [['province'], 'required','message'=>'You need to select province.'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'cityName.province.prov_name'=>'Province',//son2x:from the view.php file
            'id'=>'City / Municipality',//son2x:from the view.php file
            'city_code' => 'City / Municipality',
            'kc_classification' => 'Kc Classification',
            'cluster' => 'Cluster',
            'grouping' => 'Grouping',
            'priority' => 'Priority',
            'launch_year' => 'Launch Year',
        ];
    }

     public static function get_cities($prov_code){
        $select = "SELECT * FROM lib_cities where prov_code=$prov_code";
        $query = Yii::$app->db->createCommand($select)->queryAll();
        return $query;
    }

    //the first that works
    /*public function getCityName()
    {
      return $this->hasOne(LibCities::className(),['city_code'=>'city_code']);
    }*/

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

}

Tbl_TargetCitiesSearch型号

<?php

namespace backend\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use backend\models\TblTargetCities;

/**
 * TblTargetCitiesSearch represents the model behind the search form about `backend\models\TblTargetCities`.
 */
class TblTargetCitiesSearch extends TblTargetCities
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [[ 'grouping', 'launch_year'], 'integer'],
            [['id','city_code', 'kc_classification', 'cluster', 'priority'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = TblTargetCities::find();

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        $query->joinWith('cityName');

        $query->andFilterWhere([
            'id' => $this->id,
            'grouping' => $this->grouping,
            'launch_year' => $this->launch_year,
        ]);

       /* $query->andFilterWhere(['like', 'city_code', $this->city_code])
            ->andFilterWhere(['like', 'kc_classification', $this->kc_classification])
            ->andFilterWhere(['like', 'cluster', $this->cluster])
            ->andFilterWhere(['like', 'priority', $this->priority]);   */

        $query->andFilterWhere(['like', 'kc_classification', $this->kc_classification])
            ->andFilterWhere(['like', 'cluster', $this->cluster])
            ->andFilterWhere(['like', 'priority', $this->priority])
            ->andFilterWhere(['like', 'lib_cities.city_name', $this->city_code]);


        return $dataProvider;
    }

}

LibCities 模型

<?php

namespace backend\models;

use Yii;

/**
 * This is the model class for table "lib_cities".
 *
 * @property string $city_code
 * @property string $city_name
 * @property string $prov_code
 * @property integer $is_Urban
 * @property integer $locked
 * @property integer $app_target_hh
 * @property integer p_areas
 */
class LibCities extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'lib_cities';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['city_code', 'city_name', 'prov_code', '4p_areas'], 'required'],
            [['is_Urban', 'locked', 'app_target_hh', '4p_areas'], 'integer'],
            [['city_code', 'prov_code'], 'string', 'max' => 9],
            [['city_name'], 'string', 'max' => 100]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'city_code' => 'City Code',
            'city_name' => 'City Name',
            'prov_code' => 'Prov Code',
            'is_Urban' => 'Is  Urban',
            'locked' => 'Locked',
            'app_target_hh' => 'App Target Hh',
            '4p_areas' => '4p Areas',
        ];
    }

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



}

LibProvinces 模型

<?php

namespace backend\models;

use Yii;

/**
 * This is the model class for table "lib_provinces".
 *
 * @property string $prov_code
 * @property string $prov_name
 * @property string $region_code
 */
class LibProvinces extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'lib_provinces';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['prov_code', 'prov_name', 'region_code'], 'required'],
            [['prov_code', 'region_code'], 'string', 'max' => 9],
            [['prov_name'], 'string', 'max' => 60]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'prov_code' => 'Prov Code',
            'prov_name' => 'Prov Name',
            'region_code' => 'Region Code',
        ];
    }
}

Index.php 文件

<?php

use yii\helpers\Html;
use yii\grid\GridView;

/* @var $this yii\web\View */
/* @var $searchModel backend\models\TblTargetCitiesSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */

$this->title = 'Coverage';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="tbl-target-cities-index">

    <h1><?= Html::encode($this->title) ?></h1>
    <?php // echo $this->render('_search', ['model' => $searchModel]); ?>

    <p>
        <?= Html::a('Add new City/Municipality', ['create'], ['class' => 'btn btn-success']) ?>
    </p>

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

            [
                'attribute'=>'city_code',
                'value'=>'cityName.city_name',
                //'contentOptions'=>['style'=>'width: 120px;']
            ],
            [
              'attribute'=>'kc_classification',
              //'contentOptions'=>['style'=>'width: 120px;']
            ],
            [
                'attribute'=>'cluster',
                //'contentOptions'=>['style'=>'max-width: 100px;']
            ],
            'grouping',
             'priority',
            'launch_year',

            ['class' => 'yii\grid\ActionColumn',
            'contentOptions'=>['style'=>'width: 70px;']],
        ],
    ]); ?>

</div>

按升序排列的示例视图 -(无法正常工作)。

降序排列

  1. 在您的网格搜索中添加以下代码

    //it's for sort by city name
    $dataProvider->sort->attributes['cityName'] = [
        'asc' => ['lib_cities.cityName' => SORT_ASC],
        'desc' => ['lib_cities.cityName' => SORT_DESC],
    ];
    
    // it's sort by prov_name
    $dataProvider->sort->attributes['province'] = [
        'asc' => ['lib_provinces.prov_name' => SORT_ASC],
        'desc' => ['lib_provinces.prov_name' => SORT_DESC],
    ];
    
  2. 在您的网格视图代码中添加以下代码

    [
            'attribute'=>'city_code',
            'value'=>'cityName.city_name',
            //'contentOptions'=>['style'=>'width: 120px;']
    ],
    [
            'attribute'=>'province',
            'value'=>'cityName.province.prov_name',
            //'contentOptions'=>['style'=>'width: 120px;']
    ],
    

我通过将 search 方法更改为以下内容来弄清楚排序...

 public function search($params)
{
    $query = TblTargetCities::find();

    $query->joinWith('cityName');

    $dataProvider = new ActiveDataProvider([
        'query' => $query,
    ]);


    $dataProvider->sort->attributes['city'] = [
    // The tables are the ones our relation are configured to
    // in my case they are prefixed with "tbl_"
    'asc' => ['lib_Cities.city_name' => SORT_ASC],
    'desc' => ['lib_Cities.city_name' => SORT_DESC],
];

    $this->load($params);

    if (!$this->validate()) {
        // uncomment the following line if you do not want to any records when validation fails
        // $query->where('0=1');
        return $dataProvider;
    }



    $query->andFilterWhere([
        'id' => $this->id,
        'grouping' => $this->grouping,
        'launch_year' => $this->launch_year,
    ]);

   /* $query->andFilterWhere(['like', 'city_code', $this->city_code])
        ->andFilterWhere(['like', 'kc_classification', $this->kc_classification])
        ->andFilterWhere(['like', 'cluster', $this->cluster])
        ->andFilterWhere(['like', 'priority', $this->priority]);   */

    $query->andFilterWhere(['like', 'kc_classification', $this->kc_classification])
        ->andFilterWhere(['like', 'cluster', $this->cluster])
        ->andFilterWhere(['like', 'priority', $this->priority])
        ->andFilterWhere(['like', 'lib_cities.city_name', $this->city_code]);

    return $dataProvider;
}

参考:HERE