简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM