GSTAR
(Omzy83)
December 9, 2010, 9:27pm
1
I store the user’s date of birth in my database table, and I have a function in my User model which calculates the user’s age. This is all good and well when retrieving the user’s age, but what about when I want to query the database for users of a specific age, or users between two specific ages?
What is the correct method of doing this? How do I code this in CDbCriteria?
Chris83
(Cniska)
December 9, 2010, 10:48pm
2
I store the user’s date of birth in my database table, and I have a function in my User model which calculates the user’s age. This is all good and well when retrieving the user’s age, but what about when I want to query the database for users of a specific age, or users between two specific ages?
What is the correct method of doing this? How do I code this in CDbCriteria?
I would probably store the age as a separate field and have it updated somehow (script running on crontab or similar). That way you could easily do such queries.
iivano71
(Igor Zg1987)
December 9, 2010, 10:51pm
3
I store the user’s date of birth in my database table, and I have a function in my User model which calculates the user’s age. This is all good and well when retrieving the user’s age, but what about when I want to query the database for users of a specific age, or users between two specific ages?
What is the correct method of doing this? How do I code this in CDbCriteria?
Best way for that is eg.user is 11-12-1987 like me and the second one is 11-12-1988
AGE is name of your date of birth column
$user = User::model()->findAll(array(
'criteria'=>array(
'select'=>'user',
'condition'=>'WHERE AGE BETWEEN \'1987-12-11\' AND \'1988-12-11\' '
)
));
umutau
(Umutau)
December 9, 2010, 11:00pm
4
I don’t think this is the best but this should working
the age between 5 to 10 for example
$min=10;
$max=5;
$criteria=new CDbCriteria();
$criteria->condition='dateOfBirth between :minAge and :maxAge';
$criteria->params=array(':minAge'=>date('Y-m-d', mktime(0, 0, 0, date("m") , date("d"), date("Y") - $minAge)), ':maxAge'=>date('Y-m-d', mktime(0, 0, 0, date("m") , date("d"), date("Y") - $maxAge)));
$userList=User::model()->findAll($criteria);
zaccaria
(Matteo Falsitta)
December 10, 2010, 7:26am
6
To store the age is not a great idea, you have just to manke 2 calculation in php.
For example you can use strtotime for create the dates for search:
$criteria->params=array(
':minAge'=> date('Y-m-d',strtotime("- {$this->min_age} years"),
':maxAge'=> date('Y-m-d',strtotime("- {$this->max_age} years"));
<?php echo)?>
This funcion will work correctly even with month or days intervals
mbi
(mbi)
December 10, 2010, 3:57pm
7
$criteria->condition = 'timestampdiff( year, birthday, curdate( ) ) > 33'
timestampdiff is mysql only
http://blog.mbischof.de/alter-berechnen