2016-11-30 73 views
1

我正在努力解決如何在我的網格中使用過濾器時從SqlDataProvider生成它。SqlDataProvider過濾器

目前我的樣板工程,像這樣:

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

如果沒有一個有效記錄應該如何進行?搜索車型似乎都可以基於AR,並呼籲在控制器:

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

其中$ searchModel功能是這樣開始的:

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

    // add conditions that should always apply here 

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

我已經開始改變搜索()函數是更多類似這樣的,但不知道我要去了解它的正確方法:

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

    // add conditions that should always apply here 

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

由於它的錯誤與

的preg_match()預計參數2是串,對象給出

回答

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 
    ], 
]); 
+0

謝謝,我剛剛明白了這一點 – Jonnny

1

對於一個ActiveRecord(由GII生成)realetd到你有modelSearch.php THA containt搜索功能

在該模型情況下是

/** 
* @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變種如:

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

這一點,如果,如果你對你的模型,或者你的dataProvider,你可以重複一個類似的模式需要一個類似的行爲

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

它不具有的SqlDataProvider工作。 – nicolascolman