switch拼接where條件

yaoxs發表於2021-05-14

我想唯一美中不足的是用了迴圈,但是從閱讀程式碼的角度看比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];
    }
本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章