2015-04-28 12 views
9

Ho un'app Syfmony2 con una tabella che ha un campo data. Questo campo data è di tipo datetime.Confrontare le date tra i datetimes con Doctrine

Ho bisogno di ottenere tutte le entità che hanno la stessa data di adesso.

Ma se faccio:

$now = new \DateTime(); 
$data = $entityRepository->findByDate($now); 

ottengo 0 risultati, perché la dottrina è confrontando l'oggetto datetime, e ho bisogno di confrontare solo l'anno, mese e giorno, non ore ... solo oggetto de Data , non il datetime.

Qualche idea? Grazie: D

risposta

19

vedo in questo modo semplice:

$now = new \DateTime(); 

$data = $entityRepository->getByDate($now); 

poi nel repository

public function getByDate(\Datetime $date) 
{ 
    $from = new \DateTime($date->format("Y-m-d")." 00:00:00"); 
    $to = new \DateTime($date->format("Y-m-d")." 23:59:59"); 

    $qb = $this->createQueryBuilder("e"); 
    $qb 
     ->andWhere('e.date BETWEEN :from AND :to') 
     ->setParameter('from', $from) 
     ->setParameter('to', $to) 
    ; 
    $result = $qb->getQuery()->getResult(); 

    return $result; 
} 
+0

Grazie mille! Molto utile. – user3396420

+0

Quando sei pronto per passare al livello di codifica successivo, potresti leggere questo articolo sull'oggetto valore e sulla precisione temporale. http://rosstuck.com/precision-through-imprecision-improving-time-objects – goto

1

C'è una differenza tra i tipi di date e datetime in dottrina.

Data: Tipo che mappa un datetime di SQL per un oggetto PHP DateTime.

datetime: tipo che esegue il mapping di un oggetto DATETIME/TIMESTAMP SQL a un oggetto DateTime PHP.

Assicurarsi di aver impostato il tipo di colonna al posto di datedatetime.

In alternativa, come soluzione alternativa, è possibile ottenere il giorno dalla data originale1 e quindi effettuare la ricerca tra lo stesso giorno2 -> 00:00:00 e lo stesso giorno 3 -> 23:59:59 utilizzando un'abitudine metodo di deposito.

0

Metodo repository

public function getDays(\DateTime $firstDateTime, \DateTime $lastDateTime) 
{ 
    $qb = $this->getEntityManager()->createQueryBuilder() 
     ->select('c') 
     ->from('ProjectBundle:Calendar', 'c') 
     ->where('c.date BETWEEN :firstDate AND :lastDate') 
     ->setParameter('firstDate', $firstDateTime) 
     ->setParameter('lastDate', $lastDateTime) 
    ; 

    $result = $qb->getQuery()->getResult(); 

    return $result; 
} 

E l'azione

public function calendarAction() 
{ 
    $currentMonthDateTime = new \DateTime(); 
    $firstDateTime = $currentMonthDateTime->modify('first day of this month'); 
    $currentMonthDateTime = new \DateTime(); 
    $lastDateTime = $currentMonthDateTime->modify('last day of this month'); 

    $days = $this->getDoctrine() 
     ->getRepository('ProjectBundle:Calendar') 
     ->getDays($firstDateTime, $lastDateTime); 

    return ['days' => $days]; 
}