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']])
If I understand you well, you could use something like this:
Model::find()->orWhere(['brand' => 'brand1])
->orWhere(['id' => 'brand2'])->all();
where()
can take an array to create sql along the lines of
SELECT * FROM car WHERE brand in ('brand1', 'brand2');
using this construct you can generate an array of brands you wish to return then use the following ActiveQuery.
$brands = ['BMW', 'DODGE'];
$query = Car::find()->where(['brand' => $brands])->all();
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.