如何将条件绑定到yii2活动记录查询?

时间:2017-10-05 14:38:06

标签: jquery 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 个答案:

答案 0 :(得分: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()实际获取数据。