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条件下碰到between时,between语句如何处理呢?
php Yii2 model :: find()具有默认的WHERE条件