Yii2 where()变量条件

问题描述 投票:1回答:2

我想要当currency = 'sum'排序和Where(['between', 'price', $min_price, $max_price]) and when currency = 'y.e.' sort by andWhere(['between', 'price', $min_price*2, $max_price*2])。如何在sql中编写yii2查询?

$anmt_t = (new \yii\db\Query())
    ->select(['*'])
    ->from('anmt')
    ->where(['status' => 'confirmed'])
    ->andWhere(['between', 'price', $min_price, $max_price, when (currency = 'sum')])
    ->andWhere(['between', 'price', $min_price*2, $max_price*2, when (currency = 'y.e.')])
    ->all();
yii2
2个回答
2
投票

尝试使用CASE

$anmt_t = (new \yii\db\Query())
        ->select(['*'])
        ->from('anmt')
        ->where(['status' => 'confirmed'])
        ->andWhere('
            CASE
                WHEN currency = "sum" THEN price BETWEEN :mp1 AND :mx1
                WHEN currency = "y.e." THEN price BETWEEN :mp2 AND :mx2
            END
        ')
        ->params([
            'mp1' => $min_price,
            'mx1' => $max_price,
            'mp2' => $min_price * 2,
            'mx2' => $max_price * 2,
        ])
        ->all();

没有测试过


1
投票

我个人赞成使用Yii2,而不是写一个长查询

$condition = currency == 'y.e.' ? ['between', 'price', $min_price *2, $max_price*2] : ['between',  'price', $min_price, $max_price];

然后

$anmt_t = (new \yii\db\Query())
    ->select(['*'])
    ->from('anmt')
    ->where(['status' => 'confirmed'])
    ->andWhere($condition)
    ->all();
© www.soinside.com 2019 - 2024. All rights reserved.