Reputation: 536
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();
Upvotes: 0
Views: 4591
Reputation: 9358
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
}
}
Upvotes: 2
Reputation: 25302
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
}
Upvotes: 7