Search code examples
phpyiicriteria

How to set multiple condition on criteria for CActiveDataProvider?


I'm on project of YII. I have Production table, where I have category_id and brand_id two column. Now what I want to do is, just use the CActiveDataProvider to fetch those particular rows to the $dataprovider which has those category_id and brand_id in my $cat and $brnd array. I made it for category_id, but I am not getting any thing how to put both of them on the condition. Here is my code, please help.

$dataProvider=new CActiveDataProvider(Production::model(),
      array(
     'criteria'=>array('condition' => 'category_id IN ('.implode(',',$cat).')'),
     'pagination' => array('pageSize'=>Yii::app()->params['productsPerPage']),
    )
);

Solution

  • Use addInCondition of CDbCriteria:

    $criteria=new CDbCriteria;
    $criteria->addInCondition('category_id',$cat,'AND');
    $criteria->addInCondition('brand_id',$brnd,'AND');
    $dataProvider=new CActiveDataProvider(
        'Production',
        array(
            'criteria'=>$criteria,
            'pagination' => array('pageSize'=>Yii::app()->params['productsPerPage']),
        )
    );
    

    The last parameter of addInCondition specifies how the condition will be appended to the existing conditions, so if you want

    category_id IN (x,y,z) AND brand_id IN (a,b,c)
    

    i.e AND then you don't need to specify the 3rd parameter (default is AND), but if you want OR, as in

    category_id IN (x,y,z) OR brand_id IN (a,b,c)
    

    then you need to use

    $criteria->addInCondition('brand_id',$brnd,'OR');