Yii2 GridView implement Filter and Sort for Values for related Table of foreign Table

后端 未结 2 1363
礼貌的吻别
礼貌的吻别 2021-01-22 16:04

I have 3 Tables:

CREATE TABLE tabCve
(
    intCveID INTEGER NOT NULL AUTO_INCREMENT,
    strNumber VARCHAR(20) NOT NULL,
    fltScore FLOAT(0),
    strDescriptio         


        
2条回答
  •  没有蜡笔的小新
    2021-01-22 16:22

    visit a complete tutorial about this question in :

    http://www.yiiframework.com/wiki/851/yii2-gridview-sorting-and-searching-with-a-junction-table-column-many-to-many-relationship/

    according to this tutorial you should : 1. set your related table attribute as public in search model like this :

    public $groupname;
    

    2 . include attribute in the rules :

        public function rules() {
            return [
                [['id', 'gender', 'status', 'sentstatus'], 'integer'],
                [['groupname', 'addeddate', 'updateddate'], 'safe'],
            ];
        }
    
    1. change default query to following code in function search() in search model :

      public function search($params) {
      $query = Contacts::find()->innerJoinWith('groups', true);
      
      
    2. and in andfilterwhere add wanted attribute . like this :

      $query->andFilterWhere(['like', 'firstname', $this->firstname])
                     ... 
                      ->andFilterWhere(['like', 'groupname', $this->groupname]);
      

    in your view class and in Gridview your wanted column should like this :

    'columns' => [
                    ...
                [
                    'attribute' => 'tags',
                    'format' => 'raw',
                    'value' => function ($data) {
                        $groups= '';
                        foreach ($data->groups as $group) {
                            $groups .= '' .
                            $group->group_name . ' | ';
                        }
                        return $groups;
             },
            'filter' => ArrayHelper::map(group::find()->asArray()->all(), 'group_name','group_name'),
                    ],
    

    and if table relation is hasOne() you should read this tutorial :

    http://www.yiiframework.com/wiki/653/displaying-sorting-and-filtering-model-relations-on-a-gridview/

提交回复
热议问题