我想唯一美中不足的是用了循环,但是从阅读代码的角度看比if好太多了。也不知道有没有更好的写法。
public function spliceWhere($search_data){ | |
$where = ' 1 = 1'; | |
$bind = []; | |
foreach($search_data as $key => $value){ | |
switch($key){ | |
case 't.uid': | |
case 't.info_id': | |
case 't.seller_id': | |
if($value !== ''){ | |
$bind[str_replace('.','',$key)] = $value; | |
$where = $where.' AND '.$key.'= :'.str_replace('.','',$key).''; | |
} | |
break; | |
case 'u.name': | |
case 't.tel': | |
case 'i.title': | |
case 's.name': | |
if($value != ''){ | |
$bind[str_replace('.','',$key)] = '%'.$value.'%'; | |
$where = $where.' AND '.$key.' like :'.str_replace('.','',$key); | |
} | |
break; | |
case 't.type': | |
if($value !== '' && ($value == 0 || $value == 1)){ | |
$bind[str_replace('.','',$key)] = $value; | |
$where = $where.' AND '.$key.'= :'.str_replace('.','',$key).''; | |
} | |
break; | |
case 'start_date': | |
if($value != ''){ | |
$where = $where.' AND created_time >= '.strtotime($value); | |
} | |
break; | |
case 'end_date': | |
if($value != ''){ | |
$where = $where.' AND created_time <= '.strtotime($value); | |
} | |
break; | |
} | |
} | |
return ['where' =>$where,'bind' => $bind]; | |
} |
还有一种写法是使用1=1
public function spliceWhere($search_data){ | |
$where = ' 1 = 1 '; | |
$bind = []; | |
$name = 'and 1=1 '; | |
$unit_id = ' and 1=1 '; | |
if(!empty($search['name'])){ | |
$name = "and name like ? "; | |
$bind[] = '%'.$search['name'].'%'; | |
} | |
$where .= $name; | |
if(!empty($search['unit_id'])){ | |
$unit_id = "and unit_id = ? "; | |
$bind[] = $search['unit_id']; | |
} | |
$where .= $unit_id; | |
return [ | |
'where' => $where, | |
'bind' => $bind | |
]; | |
} | |