这是一个完全优化的问题,我有像这样的分页查询
$this->paginate = array(
'fields' => array(
'DISTINCT Contact.contact_id',
'Contact.first_name',
'Contact.last_name',
'Contact.email',
'Contact.created',
'ContactGroup.name',
),
'conditions' => array(
$this->conditions,
'ContactsContactGroup.contact_group_id'=>$viewList,
isset($keywordQuery)?$keywordQuery:"",
),
'limit' => 5,
'group' => array('Contact.contact_id')
);
$data = $this->paginate('ContactsContactGroup');
$data = $this->paginate('ContactsContactGroup');
在每个if和else语句中调用此查询,我有if
和else
的四个条件,并且在所有条件下都会编写上面的代码。
我想优化,并避免在任何条件下的大行代码,我如何优化它,任何答案将不胜感激。
答案 0 :(得分:1)
您可以在类中使用另一个返回数组的方法,而不是在任何地方发布它。添加以下代码
private function getPaginate($viewList, $keywordQuery) {
$this->paginate = array( 'fields' => array( 'DISTINCT Contact.contact_id', 'Contact.first_name', 'Contact.last_name', 'Contact.email', 'Contact.created', 'ContactGroup.name', ), 'conditions' => array( $this->conditions, 'ContactsContactGroup.contact_group_id'=>$viewList, isset($keywordQuery)?$keywordQuery:"", ), 'limit' => 5, 'group' => array('Contact.contact_id') );
//optional: return the result
return $this->paginate;
}
然后你可以使用
$this->getPaginate( $viewlist, $keywordQuery );
$data = $this->paginate('ContactsContactGroup');
$data = $this->paginate('ContactsContactGroup');
答案 1 :(得分:1)
我在搜索页面上使用常规练习我会继续在if和else中添加条件,并在最后将其连接到主查询。在你的情况下,我认为我们可以这样做:
//here is your if and else statement
$condition = array();
if(someconditions) {
$condition['user'] = 'suresh'; //your conditions
else if(some conditions)
$condition['email'] ='abc@gmail.com';
//And than add it to main query
$this->paginate = array(
'fields' => array(
'DISTINCT Contact.contact_id',
'Contact.first_name',
'Contact.last_name',
'Contact.email',
'Contact.created',
'ContactGroup.name',
),
'conditions' => array(
$condition
'ContactsContactGroup.contact_group_id'=>$viewList,
isset($keywordQuery)?$keywordQuery:"",
),
'limit' => 5,
'group' => array('Contact.contact_id')
);
$data = $this->paginate('ContactsContactGroup');
$data = $this->paginate('ContactsContactGroup');