[英]how to manipulate dates in doctrine
i have this date field (date_born) in a table in my bd, which is the date of birth of a person (type: date). 我在bd的表格中有此日期字段(date_born),这是一个人的出生日期(类型:日期)。
im using codeignater, and im also using doctrine. 我使用codeignater,我也使用教义。
the thing is that i want to count how many people are adults and how many are kids, so i built this: 问题是我想算出成年人有多少人,孩子有多少人,所以我建立了这个:
public function countAdults(){
$this->qb = $this->em->createQueryBuilder();
$this->qb->select('count(u)')
->from($this->tbl_name, 'u')
->where(
$this->qb->expr()->eq("u.date_born >'1995-01-01'")
);
$query = $this->qb->getQuery();
return $query->getSingleScalarResult();
}
this is clearly, returning an error. 显然,这将返回错误。
How can i rebuild this, in an optimus way, to count the people who was born before 1995? 我如何才能以最佳的方式重建这个数字,以计算1995年之前出生的人? (now 18) (现在18岁)
I recommend the following 我建议以下
lte
expression to compare the dates instead of evaluating with eq
使用lte
表达式比较日期,而不用eq
求值 DateTime
as Doctrine will happily accept that, and in general prefers objects over anything else. 提供PHP的DateTime
实例,因为Doctrine会很乐意接受它,并且通常更喜欢对象。 DateTime
automatically calculate when 18 years ago was, so that you don't have to change it each year. 要使此DateTime
实例自动计算18年前的时间,因此您不必每年都进行更改。 setParameters()
method. 用setParameters()
方法绑定此对象。 Method: 方法:
public function countAdults()
{
$eighteenYearsAgo = new \DateTime();
$eighteenYearsAgo->modify('-18 years');
$this->qb = $this->em->createQueryBuilder();
$this->qb->select('count(u)')
->from($this->tbl_name, 'u')
->where(
$qb->expr()->lte('u.date_born', ':date_born'))
)
->setParameters(array(
'date_born' => $eighteenYearsAgo,
))
;
return $this->qb->getQuery()->getSingleScalarResult();
}
this is what i did to build a solution for my previous question, 这就是我为上一个问题建立解决方案的过程,
I put this method in my admin: 我将此方法放在管理员中:
public function controlAge(){
$date = new \DateTime();
$var = $date->format('Y-m-d');
$dateArray = explode('-', $var);
$year = strval(($dateArray[0])-(18));
$month = $dateArray[1];
$day = $dateArray[2];
$d = $year.'-'.$month.'-'.$day;
$newDate = date('Y-m-d', strtotime($d));
return $newDate;
}
which calculates the date based on actual date, to control if a user is an adult or not (+18), so then when i do the consult in doctrine (in the dataservice) i just have to do a simple thing: sending the date "calculated" 它根据实际日期计算日期,以控制用户是否是成年人(+18岁),因此当我在教义中(在数据服务中)进行咨询时,我只需要做一个简单的事情:发送日期“计算”
public function countAdults($fecha){
$this->qb = $this->em->createQueryBuilder();
$this->qb->select('count(u)')
->from($this->tbl_name, 'u')
->where('u.date_born <= :var')
->setParameter('var', $fecha);
$query = $this->qb->getQuery();
return $query->getSingleScalarResult();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.