3

大家好,我有一个带有 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,
            ]
        );

模型搜索:

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(...)

谢谢

4

1 回答 1

1

更简单(但不是很舒服)的方法是模拟“andFilterWhere”行为:

if (isset($param['your_field'])){
    $query .= " AND your_table.your_filed =  '" . $param['your_field ."';"
}

这应该对所有过滤器字段重复。

于 2016-04-22T14:25:33.323 回答