php - How to build this sql query by queryBuilder in Yii2?
How can I get following query in Yii2 framework using queryBuilder? I want to use a operator format, but I can't understand what can I do with the OR condition...
SELECT "user_data".* FROM "user_data" LEFT JOIN "user" ON "user_data"."user_id" = "user"."id" WHERE (create_date <= NOW() - INTERVAL '1 WEEK') AND ((("user_id"='1') and ("last_visit" IS NULL)) OR ("email_status"=0));
For now my code looks like this:
UserDataModel::find()
->joinWith('user')
->where("create_date <= NOW() - INTERVAL '1 WEEK'")
->andWhere(
[
'and',
['is', 'last_visit', null],
['in', 'user_id', $array],
['or', ['email_status' => self::STATUS_INACTIVE]],
]
)
->createCommand()->getRawSql();
And this code generates this query:
SELECT "user_data".* FROM "user_data" LEFT JOIN "user" ON "user_data"."user_id" = "user"."id" WHERE (create_date <= NOW() - INTERVAL '1 WEEK') AND (("last_visit" IS NULL) AND ("user_id"='1') AND ("email_status"=0))
How to fix it?
Answer
Solution:
You need to nest conditions in this way:
UserDataModel::find()
->joinWith('user')
->where("create_date <= NOW() - INTERVAL '1 WEEK'")
->andWhere([
'or'
[
'and',
['is', 'last_visit', null],
['in', 'user_id', $array],
],
['email_status' => self::STATUS_INACTIVE],
])
->createCommand()
->getRawSql();
Source