如何在yii2中通过querybuilder构建这个sql查询?

0s0u357o  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(332)

如何使用querybuilder在yii2框架中获得以下查询?我想使用运算符格式,但我不明白我能用或条件做什么。。。

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

目前,我的代码如下所示:

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

这个代码生成了这个查询:

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

如何修复?

smdnsysy

smdnsysy1#

您需要以这种方式嵌套条件:

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

相关问题