简体   繁体   中英

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).

im using codeignater, and im also using doctrine.

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? (now 18)

I recommend the following

  • Use the lte expression to compare the dates instead of evaluating with eq
  • Provide an instance of PHP's DateTime as Doctrine will happily accept that, and in general prefers objects over anything else.
  • To make this instance of DateTime automatically calculate when 18 years ago was, so that you don't have to change it each year.
  • To bind this object with the setParameters() method.

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"

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();    
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM