Search code examples
databaseyiicriteria

Yii CActiveDataProvider filter by date range criteria


I'm working with Yii 1.1.8. Trying to limit the $dataProvider source by date in a controller action. I want to filter the dataset to show only the recent 2 year entries, but couldn't get it to work.

I got two records in the Event table where one is dated 2 months ago and the other is dated 4 years ago.

Tried:

$dataProvider=new CActiveDataProvider('Event', array(
                    'criteria'=>array(
                        'condition'=>'date >= '.date('Y-m-d', strtotime('-2 years')). ' AND  date <='. date('Y-m-d'),
                    ),
                ));

and

$dataProvider=new CActiveDataProvider('Event', array(
                    'criteria'=>array(
                        'condition'=>'date >= '.date('Y-m-d', strtotime('-2 years')),
                    ),
                ));

and

$dataProvider=new CActiveDataProvider('Event', array(
                    'criteria'=>array(
                        'condition'=>'date BETWEEN '.date('Y-m-d', strtotime('-2 years')).' AND '. date('Y-m-d'),
                    ),
                ));

All returned with "No results found". What am I doing wrong? It seems it should be something simple, but I'm stumped.


Solution

  • It's easier to create a new CDbCriteria and then pass the criteria object into the second param of the CActiveDataProvider.

    http://www.yiiframework.com/doc/api/1.1/CDbCriteria#addBetweenCondition-detail

    $criteria = new CDbCriteria; 
    $criteria->addBetweenCondition($column, $valueStart, $valueEnd, 'AND');
    
    $dataProvider=new CActiveDataProvider('Event', array('criteria'=>$criteria));