大家好,我有一个带有SQLDataProvider的网格视图,我正在做ModelSearch。互联网上的每个教程都使用ActiveDataProvider,我不想使用ActiveRecord,因为我正在使用我的数据库。
所以我的问题是:如何在MyModelSearch的搜索方法中添加过滤器?
这是我的代码:
控制器:
$queryTR = Yii::$app->db->createCommand(
"select idTypeRessource, nomTypeRessource from type_ressource"
)->queryAll();
$typeRessource = ArrayHelper::map($queryTR, 'idTypeRessource', 'nomTypeRessource');
$searchModel = new RessourceSearch();
$dataProvider = $searchModel->search(Yii::$app->request->get());
$model = $dataProvider->getModels();
return $this->render('ressource',
[
'dataProvider' => $dataProvider,
'searchModel' => $searchModel,
'model' => $model,
'typeRessource' => $typeRessource,
]
);
ModelSearch:
class RessourceSearch extends Ressource
{
public $nomRessource;
public $idTypeRessource;
public $idEtatRessource;
public $dateRecherche;
public function rules()
{
/*...*/
}
public function search($param)
{
$query = "select idTypeRessource, nomRessource, nomTypeRessource, nomEtatRessource,
date_format(tr.dateDebut, '%d/%m/%Y %H:%i') as trDateDebut,
date_format(tr.dateFin, '%d/%m/%Y %H:%i') as trDateFin,
date_format(er.dateDebut, '%d/%m/%Y %H:%i') as erDateDebut,
date_format(er.dateFin, '%d/%m/%Y %H:%i') as erDateFin
from ressource
join historique_type_ressource tr using (idRessource)
join type_ressource using(idTypeRessource)
join historique_etat_ressource er using (idRessource)
join etat_ressource using (idEtatRessource)";
$count = \Yii::$app->db->createCommand(
"select count(*) from (" . $query . ") as req"
)->queryScalar();
$dataProvider = new SqlDataProvider([
'sql' => $query,
'key' => 'nomRessource',
'totalCount' => $count,
'pagination' => [
'pageSize' => 15,
],
]);
$dataProvider->sort->attributes['nomRessource'] = [
'asc' => ['nomRessource' => SORT_ASC],
'desc' => ['nomRessource' => SORT_DESC],
];
if (!($this->load($param) && $this->validate())) {
return $dataProvider;
}
return $dataProvider;
}
}
我无法添加过滤规则,因为我使用的是SQLDataProvider而不是ActiveDataProvider(最后一个你必须使用$query->andFilterWhere(...)
由于
答案 0 :(得分:1)
更简单(但不是很舒服)的方式是模仿'andFilterWhere'行为:
if (isset($param['your_field'])){
$query .= " AND your_table.your_filed = '" . $param['your_field ."';"
}
应对所有过滤器字段重复此操作。