yii2:多條件多where條件下碰到between時,between語句如何處理呢?


yii2:多條件多where條件下碰到between時,between語句如何處理呢?

我有一張表:
id,name,telphone,ticket_no,status,create_time等字段,

在出具多條件查詢時(當不涉及到時間范圍或其他范圍),可以用如下語句:

if (!empty($params['id'])) {
    		$where_condition['oid'] = $params['id'];            
    	}
    	if (!empty($params['post_name'])) {
    		$where_condition['post_name'] = $params['post_name'];           
    	}
    	if (!empty($params['telephone'])) {
    		$where_condition['telephone'] = $params['telephone'];           
    	}
    	if (!empty($params['ticket_no'])) {
    		$where_condition['ticket_no'] = $params['ticket_no'];           
    	}
    	if ($params['status'] != -1) {
    		$where_condition['status'] = $params['status'];            
    	}  
        $where_condition['delete_flg'] = 0;   
    	$count = static::find()
    	->where($where_condition)
           ->andFilterWhere(['between','CREATE_TIME',$start_date, $end_date])
    		->count();

  

當涉及到create_time時間范圍查詢時,那么問題來了,between怎么加進去?$where_condition['CREATE_TIME']='between 時間1 and 時間2' 這樣是不行的,花了一點時間查詢了下,yii2有這樣的方法:andFilterWhere,使用方法如下:

->andFilterWhere(['like1', 'name', '%a%'])

#當參數1,參數2為空時,between方法會自動過濾掉,也就是此條件會被刪除不執行
 ->andFilterWhere(['between', 'created_at', 0(參數1), 1433088000(參數2)])

  

 andFilterWhere使用說明:

當 WHERE 條件來自於用戶的輸入時,你通常需要忽略用戶輸入的空值。 例如,在一個可以通過用戶名或者郵箱搜索的表單當中,用戶名或者郵箱 輸入框沒有輸入任何東西,這種情況下你想要忽略掉對應的搜索條件, 那么你就可以使用 yii\db\Query::filterWhere() 方法來實現這個目的:

// $username 和 $email 來自於用戶的輸入$query->filterWhere([ 'username' => $username, 'email' => $email, ]); 

  

 

 

 

 

具體代碼如下:

if (!empty($params['id'])) {
    		$where_condition['oid'] = $params['id'];
            
    	}
    	if (!empty($params['post_name'])) {
    		$where_condition['post_name'] = $params['post_name'];
            
    	}
    	if (!empty($params['telephone'])) {
    		$where_condition['telephone'] = $params['telephone'];
           
    	}
    	if (!empty($params['ticket_no'])) {
    		$where_condition['ticket_no'] = $params['ticket_no'];
          
    	}
    	if ($params['status'] != -1) {
    		$where_condition['status'] = $params['status'];
           
    	}
        $start_date = $end_date = '';
        if($params['isSearch'] == 1) {
            if (!empty($params['start_date']) && !empty($params['end_date'])) {
                $start_date = strtotime($params['start_date']);
                $end_date = strtotime($params['end_date']) + 86400 - 1;
              
            }
        }
        $where_condition['delete_flg'] = 0;
       
    	
    		$count = static::find()
    		->where($where_condition)
            ->andFilterWhere(['between','CREATE_TIME',$start_date, $end_date])
    		->count();

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM