Yii2 where()变量条件

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Yii2 where()变量条件相关的知识,希望对你有一定的参考价值。

我想要当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 yiidbQuery())
    ->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();
答案

尝试使用CASE

$anmt_t = (new yiidbQuery())
        ->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();

没有测试过

另一答案

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

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

然后

$anmt_t = (new yiidbQuery())
    ->select(['*'])
    ->from('anmt')
    ->where(['status' => 'confirmed'])
    ->andWhere($condition)
    ->all();

以上是关于Yii2 where()变量条件的主要内容,如果未能解决你的问题,请参考以下文章

Yii2查询之where条件拼装

yii2数据条件查询-where专题

yii2:多条件多where条件下碰到between时,between语句如何处理呢?

php Yii2 model :: find()具有默认的WHERE条件

Yii2 mongodb 扩展的where的条件增加大于 小于号

Yii2 mongodb 扩展的where的条件加入大于小于号浅析(转)