Conditional WHERE clause

I’m wondering the proper way (I managed to make it work using an if(){… but it is far from elegant and I’m assuming there is a much better way to approach this) to handle build a query (for a activeDropDownList) which has a conditional WHERE clause


the above fails in the instances in which $model->StatusId hasn’t been set yet, so how can I make it handle both situations: If $model->StatusId is defined, filter accordingly, otherwise return nothing?

Hi @DBCreator,

I would use if for this scenario.

BTW, there’s a convenient version of where that is filterWhere.

By using it, you can safely write like this:

$query->filterWhere(['StatusId' => $model->StatusId]);

This is equivalent to the following:

if (!empty($model->StatusId)) {
    $query->where(['StatusId' => $model->StatusId);

Unfortunately, it returns all when $model->StatusId is empty, while you want it to return nothing. So, a simple if is a decent solution for you scenario.