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
Pseudo-code
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
Demo::find()
->where(...) // ( condition one
->andWhere(...) // AND condition two )
->orWhere(...) // OR (!) ( condition three
->andWhere(...) // AND condition four )
Question:
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
where()
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):
Demo::find()->where([
'or',
['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 .
source to share
You can do it like this:
Demo::find()
->where('(a = :a AND b = :b)', [
':a' => 'bla',
':b' => 'bla',
])
->orWhere('(c = :c AND d = :d)', [
':c' => 'bla',
':d' => 'bla',
]);
The docs http://www.yiiframework.com/doc-2.0/yii-db-queryinterface.html#where()-detail 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.
source to share