2012-07-18 90 views
0

我有一個CakePHP應用程序,其中包含許多使用來自特定模型的數據的多個屏幕。大多數情況下,我需要檢查特定的字段(例如cookbook中的「user_active => 1」示例),但是我仍然希望能夠將該字段指定爲條件並覆蓋默認值。我的代碼有效,但是這是做到這一點的最佳方式嗎?在CakePHP中設置默認搜索值的正確方法

此外,$ queryData字段是混合的 - 除數組之外還有什麼可能?只是NULL?

<?php public function beforeFind($queryData) { 
    if(is_array($queryData)) { 
     //query data was an array 
     if(!is_array($queryData['conditions'])) { 
      $queryData['conditions'] = array('Course.semester_id'=>SEMESTER_ID); 
     } else if (!isset($queryData['conditions']['Course.semester_id'])) { 
      $queryData['conditions']['Course.semester_id'] = SEMESTER_ID; 
     } 
    } 
} ?> 

回答

0

我會建議在您的模型中自定義findCourses($options)函數。這樣,您可以設置所有默認條件,並覆蓋在$options中傳遞的所有內容。

下面是一個例子:

//Article model 

public function articles($opts = null) { 

    //initialize 
    $params = array(); 
    $findType = 'all'; 
    $params['conditions'] = array(); 

    //status 
    if(!empty($opts['status'])) { 
     array_push($params['conditions'], array('Article.status'=>$opts['status'])); 
    } else { 
     array_push($params['conditions'], array('Article.status'=>1)); 
    } 

    //id 
    if(!empty($opts['id'])) { 
     $params['limit'] = 1; 
     $findType = 'first'; 
     array_push($params['conditions'], array('Article.id'=>$opts['id'])); 
    } 

    //slug 
    if(!empty($opts['slug'])) { 
     $params['limit'] = 1; 
     $findType = 'first'; 
     array_push($params['conditions'], array('Article.slug'=>$opts['slug'])); 
    } 

    //limit (and find type) 
    if(!empty($opts['limit'])) { 
     $params['limit'] = $opts['limit']; 
     if($opts['limit'] == 1) $findType = 'first'; 
    } 

    //order by 
    $params['order'] = array('Article.created DESC'); 
    if(!empty($opts['order'])) { 
     $params['order'] = $opts['order']; 
    } 

    //type 
    if(!empty($opts['type'])) { 
     array_push($params['conditions'], array('type'=>$opts['type'])); 
    } 

    //find type 
    if(!empty($opts['find_type'])) $findType = $opts['find_type']; 

    //slug 
    if(!empty($opts['slug'])) { 
     array_push($params['conditions'], array('slug'=>$opts['slug'])); 
    } 

    //search 
    if(!empty($opts['search'])) { 
     array_push($params['conditions'], array('Article.title LIKE' => '%'.$opts['search'].'%')); 
    } 

    //contain 
    $params['contain'] = array('MetaData', 'Tag', 'Upload'); 

    //paginate options or results 
    if(!empty($opts['paginate'])) { 
     return $params; 
    } else { 
     return $this->find($findType, $params); 
    } 

} 

在我的控制,我可以做到這一點:

$opts = array('limit'=>6, 'type'=>'gaming'); 
$articles = $this->Article->articles($opts);