假设我在gridview中将5列合并为一列,我想将列Filter函数连接起来,如下所示
SELECT strcat(Column1, Column2, Column3, Column4, Column5) as MainColumnName.
当我搜索时,我必须执行类似这样查询,
WHERE MainColumnName LIKE '%userinput%';
**问题:**如何在yii2中实现,查询的结果会反映在gridview的下拉过滤器中。
3vpjnl9f1#
最简单的方法是扩展搜索函数的功能,以便可以在dataProvider中使用结果为此,您应该正确设置你的模型以获得连接结果,例如使用getter
/* Getter for full name */ public function getMainName() { return $this->column1 . ' ' . $this->column2 . ' ' . $this->column3 . ' ' . $this->column4 . ' ' . $this->column5; } /* Your model attribute labels */ public function attributeLabels() { return [ /* Your other attribute labels */ 'mainName' => Yii::t('app', 'Main Column Name') ]; }
设置筛选和排序的搜索模型
/* your calculated attribute */ public $mainName; /* setup rules */ public function rules() { return [ /* your other rules */ [['mainName'], 'safe'] ]; } /** * setup search function for filtering and sorting * based on mainName field */ public function search($params) { $query = YourModel::find(); $dataProvider = new ActiveDataProvider([ 'query' => $query, ]); /** * Setup your sorting attributes * Note: This is setup before the $this->load($params) * statement below */ $dataProvider->setSort([ 'attributes' => [ 'id', 'mainName' => [ 'asc' => ['column1' => SORT_ASC, 'column2' => SORT_ASC, 'column3' => SORT_ASC, 'column4' => SORT_ASC, 'column5' => SORT_ASC], 'desc' => ['column1' => SORT_DESC, 'column2' => SORT_DESC, 'column3' => SORT_DESC, 'column4' => SORT_DESC, 'column5' => SORT_DESC], 'label' => 'Full Name', 'default' => SORT_ASC ], 'other_your_column' ] ]); if (!($this->load($params) && $this->validate())) { return $dataProvider; } ........ /* Setup your custom filtering criteria */ // filter by person full name $query->andWhere(" concat(column1, ' ', column2, ' ',column3, ' ',column4, ' ',column5) LIKE concat('%','" . $this-mainName . "', '%') "); return $dataProvider; }
在您的gridView中
echo GridView::widget([ 'dataProvider' => $dataProvider, 'filterModel' => $searchModel, 'columns' => [ ['class' => 'yii\grid\SerialColumn'], 'id', 'mainName', ['class' => 'yii\grid\ActionColumn'], ] ]);
您可以在此http://www.yiiframework.com/wiki/621/filter-sort-by-calculated-related-fields-in-gridview-yii-2-0/中找到一些示例
1条答案
按热度按时间3vpjnl9f1#
最简单的方法是扩展搜索函数的功能,以便可以在dataProvider中使用结果
为此,您应该
正确设置你的模型以获得连接结果,例如使用getter
设置筛选和排序的搜索模型
在您的gridView中
您可以在此http://www.yiiframework.com/wiki/621/filter-sort-by-calculated-related-fields-in-gridview-yii-2-0/中找到一些示例