Подтвердить что ты не робот

Сравните даты между датами с Doctrine

У меня есть приложение Syfmony2 с таблицей, которая имеет поле даты. Это поле даты относится к типу DateTime.

Мне нужно получить все объекты, которые совпадают с датой, как сейчас.

Но если я сделаю:

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

Я получаю 0 результатов, потому что Doctrine сравнивает объект DateTime, и мне нужно сравнивать только год, месяц и день, а не часы... только объект de Date, а не DateTime.

Любая идея? Спасибо

4b9b3361

Ответ 1

Я вижу этот простой способ:

$now = new \DateTime();

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

затем в вашем репозитории

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

Ответ 2

Метод в репозитории

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

И действие

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];
}

Ответ 3

В доктрине существует разница между типами date и datetime.

date: введите, что сопоставляет SQL DATETIME с объектом PHP DateTime.

datetime: тип, который сопоставляет SQL DATETIME/TIMESTAMP с PHP DateTime объект.

Убедитесь, что для столбца задан тип date вместо datetime.

В качестве альтернативы - в качестве обходного пути вы можете получить день с исходной даты1, а затем выполнить поиск между датой в тот же день2 → 00:00:00 и в тот же день date3 → 23:59:59, используя специальный репозиторий метод.

Ответ 4

Использование DoctrineExtensions: гораздо более простой ответ с использованием метода date() Doctrine:

class BlogRepository extends EntityRepository
{
    public function findTodaysBlogs()
    {   
        $today = new \Datetime;

        $qb = $this->createQueryBuilder('f')
            ->where('date(f.createdAt) = :today')
            ->setParameter(':today', $today);

        return $qb->getQuery()
            ->getResult();   
    }
}