假设我在gridview中将5列合并为一列,我想连接像这样的列Filter函数
SELECT strcat(Column1, Column2, Column3, Column4, Column5) as MainColumnName.
当我搜索时我必须执行这样的查询,
WHERE MainColumnName LIKE '%userinput%';
问题:如何在yii2中实现它,查询结果将反映在gridview中的下拉过滤器中。
先谢谢,
答案 0 :(得分:0)
最简单的方法是扩展搜索功能的功能,以便在dataProvider中使用结果
为此你应该
正确设置模型以获得concatenad结果,例如使用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/
中找到一些示例