Conditional orWhere clause

I have the following

$clients = ArrayHelper::map(
                        Clients::find()
                            ->orderBy(['Company' => SORT_ASC])
                            ->where(['Active' => 1])
                            ->orWhere(['ClientId' => $model->ClientId])
                            ->all(),
                        'ClientId',
                        'Company'
                    );

but the orWhere only applies if $model->ClientId has a value, it could be null. So how do I build this properly?

I’ve done

                    if (isset($model->ClientId)) {
                        $clients = ArrayHelper::map(
                            Clients::find()
                                ->orderBy(['Company' => SORT_ASC])
                                ->where(['Active' => 1])
                                ->orWhere(['ClientId' => $model->ClientId])
                                ->all(),
                            'ClientId',
                            'Company'
                        );
                    } else {
                        $clients = ArrayHelper::map(
                            Clients::find()
                                ->orderBy(['Company' => SORT_ASC])
                                ->where(['Active' => 1])
                                ->all(),
                            'ClientId',
                            'Company'
                        );
                    }

but I’m sure there’s a better way, so I thought I’d ask and learn.

Thank you

I tried

$query = Clients::find()
    ->where(['=', 'Active', 1]);
if (isset($model->ClientId)) {
    $query->orWhere(['=', 'ClientId', $model->ClientId]);
}
$query->orderBy(['Company' => SORT_ASC])
    ->all();
$clients = ArrayHelper::map(
    $query,
    'ClientId',
    'Company'
);

but I get nothing returned?

I have it solved. Documentation helped me understand it already does a check internally, so the following works

$query = Clients::find()
    ->where(['=', 'Active', 1])
    ->orWhere(['=', 'ClientId', $model->ClientId])
    ->orderBy(['Company' => SORT_ASC])
    ->all();
$clients = ArrayHelper::map(
    $query,
    'ClientId',
    'Company'
);

That said, I’m curious why I couldn’t build up my $query as shown in my previous reply (for my personal learning).

1 Like

This is really weird and it should work on your first attempt :thinking:

Ok, so I’m not loosing it, it should have worked. I will revisit the code then for personal learning/understanding.

Thank you Bizley! I truly appreciate your assistance (with all my posts).