我會建議在您的模型中自定義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);