モデルにカスタム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);