4

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']])
12
  • This should work as long as static method getCar() returns ActiveQuery instance. Commented Jan 20, 2017 at 13:04
  • @Bizley I've added what the getCar returns. I don't think thats te problem, because a single where parameter for a single column works just fine Commented Jan 20, 2017 at 13:16
  • This is weird, it should work. What do you mean by "I don't get this to work"? Is there any error or you just don't see expected results? Please test this version with or by replacing ->all(); with ->createCommand()->rawSql; and examining the output. Commented Jan 20, 2017 at 13:23
  • It only returns the all BMW's Commented Jan 20, 2017 at 13:42
  • Could you paste the result of this output? Commented Jan 20, 2017 at 13:52

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

Comments

4

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

Model::find()
             ->orWhere(['brand' => 'brand1'])
             ->orWhere(['id' => 'brand2'])
             ->all();

1 Comment

I've replaced the where with orWhere, but it still only returns the BMW's only.
2

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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.