I trying to create a between year search of people, I got it to work(se code below) but I want the user to be able to specify the age instead of the birthyear in the searchfield.
So I need to calculate "current date - age" from the searchfields and then insert it in the between-syntax somehow.
This is my code at the moment.
Model:
public $date_first;
public $date_last;
public function rules()
{
return array(
array('..., date_first, date_last', 'safe', 'on'=>'search'),
);
}
public function search()
{
$criteria=new CDbCriteria;
$criteria->with = 'people';
$criteria->compare('...');
if((isset($this->date_first) && trim($this->date_first) != "") && (isset($this->date_last) && trim($this->date_last) != ""))
$criteria->addBetweenCondition('people.date_of_birth', ''.$this->date_first.'', ''.$this->date_last.'');
}
you are camparing database date field with integer (eg. people.date_of_birth BETWEEN 11 AND 12)… I do not know what database you are using but most I know won’t work as you might expect. You have to calculate age from date_of_birth or compare dates.
"now()" is a MySQL function returning current timestamp. I did wrote that this is only an example and you should use expression proper to your db engine. The example was only to show how (and where) put expression that calculates age for every person. In fact for MySQL you should use expression like this:
$criteria->addCondition(‘TIMESTAMPDIFF(YEAR,people.date_of_birth,NOW()) BETWEEN 15 AND 22’);