SqlDataProvider过滤器

时间:2016-11-30 18:20:22

标签: yii2 filtering

当我从SqlDataProvider生成过滤器时,我正在努力研究如何在网格中使用过滤器。

目前我的模型是这样的:

SELECT 
    REGEXP_REPLACE(datewithoutdash,
    '^(\\d{2})(\\d{2})(\\d{2})(.*)$','20\\1-\\2-\\3') 
    datewithdash 
     FROM table1 WHERE datewithdash < "2016-11-10";

如果没有活动记录,应该怎么做?搜索模型似乎都基于AR并在控制器中调用:

 $sql = 'SELECT * FROM my_table';
 $provider = new SqlDataProvider([
       'sql' => $sql,
       'params' => [':start' => $param1, ':end' => $param2],
       'totalCount' => $count,
       'pagination' => [
         'pageSize' => 100
        ],
     ]);
return $provider;

$ searchModel函数的开头如下:

$searchModel->search(Yii::$app->request->queryParams);

我已经开始将search()函数更改为更像这样,但不确定我是否正确地采用它:

  public function search($params)
 {
    $query = myTable::find();

    // add conditions that should always apply here

    $dataProvider = new ActiveDataProvider([
        'query' => $query,
    ]);
    ...

因为错误

  

preg_match()期望参数2为字符串,给定对象

2 个答案:

答案 0 :(得分:2)

对于SqlDataProvider,您需要提供SQL字符串。在这里,您将提供一个查询对象,但您可以像这样获取SQL:

$query = new Query;
$query->select('*')
    ->from('my_table');

// add conditions that should always apply here

$dataProvider = new SqlDataProvider([
    'sql' => $query->createCommand()->sql,
    'pagination' => [
        'pageSize' => 100
    ],
]);

答案 1 :(得分:1)

对于一个activeRecord(由gii生成)realetd到模型,你有一个modelSearch.php包含一个搜索函数

在这种情况下是用户模型搜索

 /**
 * @param $params
 * @return ActiveDataProvider
 */
public function search($params)
{
    $query = $this->finder->getUserQuery();

    $dataProvider = new ActiveDataProvider([
        'query' => $query,
    ]);

    if (!($this->load($params) && $this->validate())) {
        return $dataProvider;
    }

    if ($this->created_at !== null) {
        $date = strtotime($this->created_at);
        $query->andFilterWhere(['between', 'created_at', $date, $date + 3600 * 24]);
    }

    $query->andFilterWhere(['like', 'username', $this->username])
        ->andFilterWhere(['like', 'email', $this->email])
        ->andFilterWhere(['registration_ip' => $this->registration_ip]);

    return $dataProvider;
}

使用适当的

组合执行过滤功能
 $query->andFilterWhere(....) 

每个都与正确的列名和param var有关,例如:

$query->andFilterWhere(['like', 'username', $this->username]);

如果您需要类似于您的模型的行为,或者您需要dataProvider,则可以重复相似的模式

$query = new Query;
$query->select('*')
      ->from('my_table');
$query->andFilterWhere('start', $param1);