Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2 query OR condition multiple values for 1 column

Tags:

sql

php

yii2

I've made an API with the Yii2 framework. But I don't know how to use the OR condition in my statement.

For example: I want to get all cars with brand BMW or DODGE.

I've tried the following:

$query = Car::getCar($lang)
         ->where(['or', ['m.brand' => 'BMW'], ['m.brand' => 'DODGE']])
         ->all();

But this doesn't work. I only get it to work with one value for m.brand.

So:

$query = Car::getCar($lang)
         ->where(['m.brand' => 'BMW'])
         ->all();

Works just fine.

Tried to put in a few other ways, but I don't get this to work.
Does anyone know what I'm doing wrong?

EDIT The getCar method returns something like:

(new Query())->select(['a.auto_id'])->from('auto_new a') 

EDIT 2 Got it to work with:

$query->andWhere(['or', ['m.brand' => 'BMW'], ['m.brand' => 'DODGE']])
like image 214
Wouter den Ouden Avatar asked Dec 18 '22 10:12

Wouter den Ouden


2 Answers

You can actually simplify it a lot by using an array with the values you need:

$query = Car::getCar($lang)
    ->where(['m.brand' => ['BMW', 'DODGE']])
    ->all();

This will execute with something like WHERE m.brand IN ('BMW', 'DODGE') which returns the result you are looking for.

like image 123
marche Avatar answered Jan 12 '23 11:01

marche


If I understand you well, you could use something like this:

Model::find()
             ->orWhere(['brand' => 'brand1'])
             ->orWhere(['id' => 'brand2'])
             ->all();
like image 39
Oleg Avatar answered Jan 12 '23 13:01

Oleg