Yii2 query with and or in where condition

1k Views Asked by At

Hi iam trying to covert this query as active record format

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)

code which i have tried

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

this will fails

2

There are 2 best solutions below

0
On

Try this one

$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();
0
On

Let's further optimize your query:

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