Yii2查询与和或在哪里条件

时间:2019-07-10 11:46:03

标签: yii2 yii2-model yii2-active-records

您好,我想隐瞒此查询为有效记录格式

SELECT cmaindb, eshdr1, ascsnr, takpplz, takpadr
FROM ts_stats
 WHERE (cmaindb = 'tam' OR cmaindb = 'soc')
 AND (nproduktiv = 1) 
 OR  (cmaindb = 'tc') 
 AND (nabrfirm = 5) 
 AND (nproduktiv = 1)

我尝试过的代码

return self::find()
     ->andWhere(['or',
       ['cmaindb'=> 'tam'],
       ['cmaindb'=> 'soc']
     ])
     ->andWhere(['nproduktiv'=>1])
     ->orWhere(['cmaindb' => 'tc'])
     ->andWhere(['nabrfirm '=>5, 'nproduktivs'=>1])
     ->all();

这将失败

2 个答案:

答案 0 :(得分:1)

尝试这个

$cmaindbs = array('tam'=>'tam', 'soc'=>'soc');
return self::find()
     ->where(['IN', 'cmaindb' , $cmaindbs])
     ->andWhere(['nproduktiv' => 1])
     ->orWhere(['cmaindb' => 'tc'])
     ->andWhere(['nabrfirm' => 5])
     ->andWhere(['nproduktivs' => 1])
     ->all();

答案 1 :(得分:0)

让我们进一步优化您的查询:

return self::find()
     ->where(['IN', 'cmaindb' , ['tam', 'soc', 'tc'])
     ->andWhere(['nproduktiv' => 1])
     ->andWhere(['nabrfirm' => 5])
     ->andWhere(['nproduktivs' => 1])
     ->all();