2017-10-05 101 views
0

鑑於此查詢:如何將條件綁定到yii2活動記錄查詢?

Customers::find() 

if(isset($request->post('hasPhone'))) 
->where(['=', 'has_phone', 1]) 

if(isset($request->post('hasEmail'))) 
->where(['=', 'has_email', 1]) 

->orderBy('id DESC'); 

我如何where條款添加到查詢,如果條件得到滿足,並跳過他們,如果他們不?

回答

1
$query = Customers::find()->orderBy('id DESC'); 

if (isset($request->post('hasPhone'))) { 
    $query->andWhere(['has_phone' => 1]); 
} 
if (isset($request->post('hasEmail'))) { 
    $query->andWhere(['has_email' => 1]); 
} 

記住實際上$query->one()$query->all()獲取數據。