0

Just a quick question. I need to create a find query in Yii2 where an andWhere is only present if a variable is true.

public function getCheckBoxItems($holiday=false)
{
    $Items = Items::find()->where(['type'=>'checkbox']);
    Yii::info(print_r($Items,1), 'c');

    if($holiday)
        $Items->andWhere(['<>','category','holiday']);

    $Items->All();
    foreach($Items as $Item)
    {
        //do something
    }
}

This doesn't work

However this deos work and i expected it to.

$Items = Items::find()->where(['type'=>'checkbox'])->andWhere(['<>','category','holiday'])->All();

How do I only add the andWhere based on the $holiday variable

Thanks in advance

Regards

Liam

UPDATE i have found one way, but i am sure there is a better way

    if($holiday)
        $Items = Items::find()->where(['type'=>'checkbox'])->andWhere(['<>','category','holiday'])->All();
    else            
        $Items = Items::find()->where(['type'=>'checkbox'])->All();
AsgarAli
  • 2,201
  • 1
  • 20
  • 32
Liam
  • 536
  • 8
  • 23

2 Answers2

7

Just to make your code more clear and readable, you should simply try :

$itemsQuery = Items::find()->where(['type'=>'checkbox']);

if($holiday)
    $itemsQuery->andWhere(['<>','category','holiday']);

$items = $itemsQuery->all();
foreach($items as $item)
{
    //do something
}
soju
  • 25,111
  • 3
  • 68
  • 70
2

You have to store $items result at each checkpoint:

public function getCheckBoxItems($holiday=false)
{
$Items = Items::find()->where(['type'=>'checkbox']);
Yii::info(print_r($Items,1), 'c');

if($holiday)
    $Items->andWhere(['<>','category','holiday']);

$Items = $Items->All();
foreach($Items as $Item)
{
    //do something
}
}
Insane Skull
  • 9,220
  • 9
  • 44
  • 63