2013-02-18 76 views
1

我在Zend Framework 2中工作并使用Doctrine查询语言。使用原则查询语言计算出生日期的年龄

我必须在用户列表页面上添加年龄过滤器。在数据库中,我使用日期格式存储了用户的出生日期。请帮助我如何使用where条件来应用我的过滤器。

$repository = $this->entityManager->getRepository('User\Entity\User'); 
$query = $repository->createQueryBuilder('u'); 
$query->where("(DATE_DIFF(CURRENT_DATE(), u.birth_date)/365)=".$search_arr['age']); 

此查询不返回任何内容。原因可能是,当我在mysql DATEDIFF(CURRENT_DATE() , u.birth_date) /365中运行它时,它会返回浮点数,例如10.29。我需要将其转换为整数进行比较。 Mysql提供了FLOOR函数,但它在DQL中不起作用。

请帮助我。

+1

你有没有尝试[this](http://docs.doctrine-project.org/zh/2.1/reference/dql-doctrine-query-language.html)解决方案? – Peon 2013-02-18 13:46:53

+0

@DainisAbols我试过这个解决方案。但它给了我FLOOR函数在DQL中不可用的错误。 – 2013-02-18 13:51:28

+4

您必须定义一个自定义的DQL函数:http://www.doctrine-project.org/blog/doctrine2-custom-dql-udfs.html – Ocramius 2013-02-18 14:42:08

回答

0

以下公式做的伎俩对我来说:

if (today - 31 <= DOB >= today - 30) i am 30. 

这就是它看起来像在DQL:

$age = intval($data['age']); 

$startDate = new \DateTime('now'); 
$startDate->modify('-'.($age+1).' years'); 

$endDate = new \DateTime('now'); 
$endDate->modify('-'.$age.' years'); 
$from = new \DateTime($startDate->format("Y-m-d H:i:s")); 
$to = new \DateTime($endDate->format("Y-m-d H:i:s")); 

$qb = $this->getEntityManager()->createQueryBuilder(); 

$qb->select('p'); 
$qb->from('MyBundle:Person', 'p'); 
$qb->andWhere('p.dateOfBirth BETWEEN :from AND :to'); 
$qb->setParameter('from', $from); 
$qb->setParameter('to', $to); 
0
$query->createQueryBuilder('u')->where(':year - substring(u.birthday,1,4) = :age and ((:month = substring(u.birthday,6,2) and :day >= substring(u.birthday,9,2)) or :month > substring(u.birthday,6,2)) or 
     :year - substring(u.birthday,1,4) - 1 = :age and ((:month = substring(u.birthday,6,2) and :day < substring(u.birthday,9,2)) or :month < substring(u.birthday,6,2))') 

     ->setParameter('year', (new \DateTime('now'))->format("Y")) 
     ->setParameter('month', (new \DateTime('now'))->format("m")) 
     ->setParameter('day', (new \DateTime('now'))->format("d")) 
     ->setParameter('age', $age); 

日期的格式年月日

相关问题