How to say (a AND b) OR (c AND d) in an ActiveRecord YII2 query?

I'm having a hard time with the YII2 ORM, which doesn't document some pretty simple typical SQL cases like


SELECT * FROM table WHERE (a=1 AND b=2) OR (a=3 AND b=4)


What I have tried:

// should represent the commented logic, but does not
    ->where(...) // ( condition one
    ->andWhere(...) // AND condition two )
    ->orWhere(...) // OR (!) ( condition three
    ->andWhere(...) // AND condition four )



In YII2, the where () method does not allow you to "nest" queries, and this is where I am stuck. YII2 only lets you say simple AND .. OR costs, never puts IO together.


source to share

3 answers


the method allows nested conditions:

Demo::find()->where(['or', ['a' => 1, 'b' => 2], ['a' => 3, 'b' => 4]]);


There are some examples in the official docs here .

More complex example (as you asked in the comment):

    ['and', ['not in', 'a' => [1, 2]], ['not in', 'b' => [3, 4]]],
    ['a' => [5, 6]], 'b' => [7, 8]],


Another example can be found in a similar question here .



You can do it like this:

    ->where('(a = :a AND b = :b)', [
        ':a' => 'bla',
        ':b' => 'bla',
    ->orWhere('(c = :c AND d = :d)', [
        ':c' => 'bla',
        ':d' => 'bla',


The docs give a pretty good explanation of where options are possible. Including how to use the subquery.

Descriptions and and or explains how to create sets differently than shown above.



Demo::find()->where('a=1 and b=2 or f=3')->one();




All Articles