简体   繁体   中英

Doctrine equivalent of in() expression with dates

Using Doctrine's QueryBuilder , I attempted to use the in() method on an array of dates but I found out it only allows string values.

/** @param DateTime[] $dates */
public function findByDate(array $dates): array {
    $qb = $this->createQueryBuilder('Event');
    $qb->andWhere($qb->expr()->in('Event.date', ':dates'));
    $qb->setParameter('dates', $dates);
    return $qb->getQuery()->getResult();
}

An exception occurred while executing 'SELECT [...]' with params [{"date":"2020-01-31 00:00:00.000000","timezone_type":3,"timezone":"Europe/Berlin"}]:
Catchable Fatal Error: Object of class DateTimeImmutable could not be converted to string

Is there any easy equivalent of in() function working with dates ? (preferably not using DQL)

Here is the solution I came up with, looping over the PHP array, building another array of eq() expressions, and then or ing everything. It does its job but needs to declare one parameter per date in the array instead of one single array parameter.

Let me know if you find some better way...

/** @param DateTime[] $dates */
public function findByDate(array $dates): array {
    $qb = $this->createQueryBuilder('Event');
    $criteria = [];
    for($i = 0; $i < count($dates); $i++) {
        $criteria[] = $qb->expr()->eq('Event.date', ":date_$i");
        $qb->setParameter("date_$i", $dates[$i]);
    }
    $qb->andWhere($qb->expr()->orX()->addMultiple($criteria));
    return $qb->getQuery()->getResult();
}

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