2011-11-16 43 views
3

我有一個使用MAX() MySQL的柱爲其中一列提供的數據的CGridView。我有與排序工作,但我無法弄清楚過濾。我認爲我可以使用CDbCriteria::compare()調用來設置它,但它不起作用。想法?CGridView濾波與骨料(分組)的功能 - 例如MAX()

我的搜索功能:

$criteria = new CDbCriteria; 
    $criteria->condition = 't.is_deleted = 0 and is_admin = 0'; 
    // get last note date 
    $criteria->select = array('t.*', 'MAX(n.visit_date) AS last_note'); 
    $criteria->join = 'LEFT JOIN notes n ON t.id = n.distributor_id'; 
    $criteria->group = 't.id'; 
    $criteria->order = 't.status'; 

    $criteria->compare('t.type', $this->type); 
    $criteria->compare('t.name', $this->name, true); 
    $criteria->compare('t.city', $this->city, true); 
    $criteria->compare('t.state', $this->state); 
    $criteria->compare('last_note', $this->last_note); 



    return new CActiveDataProvider('Distributor', array(
      'criteria' => $criteria, 
      'pagination' => array(
       'pageSize' => 20 
      ), 
      'sort' => array(
       'defaultOrder' => 'name', 
       'attributes' => array(
        'last_note' => array(
         'asc' => 'last_note', 
         'desc' => 'last_note DESC' 
        ), 
       ) 
      ), 
     )); 

在我看來,我只是設置名稱和值值。

我得到的錯誤是CDbCommand failed to execute the SQL statement: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'last_note' in 'where clause'

編輯:我發現,要做到這一點(因爲你不能在where子句中聚合函數)的唯一方法是檢查$_GET陣列的last_note值,添加一個條款。請注意,這不是參數或任何東西,我只是想粗略出來,看看它是否會工作:

if(isset($_GET['Distributor']['last_note']) && $_GET['Distributor']['last_note'] != '') { 
     $criteria->having = 'MAX(n.visit_date)=\'' . $this->last_note . "'"; 
} 

我討厭這樣的模型中使用的請求變量,但沒有太多否則我可以做。

回答

3

你在正確的軌道上。您可以使用having過濾聚合函數,如MAX()SUM()。在這樣的查詢,你應該添加一個group,否則你會在你的結果了很多的重複數據結束時,經銷商有在同一天多個音符(假設t.id是主鍵)。其次,您應該使用命名參數,而不是直接將變量放入SQL中。所以,相反的compare('last_note'...你最終的東西是這樣的:

$criteria->group = 't.id'; 
$criteria->having = 'MAX(n.visit_date) = :last_note'; 
$criteria->params = array(':last_note' => $this->last_note); 
2

爲了篩選工作,你應該有一個class屬性來存儲數據:

公共$ last_note;

否則$這個 - > last_note不會返回任何東西,你的$基準 - - >比較( 'last_note',$這個 - > last_note);不會做任何事情