简体   繁体   English

带有日期的 in() 表达式的等价原则

[英]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.使用 Doctrine 的QueryBuilder ,我尝试in()日期数组上使用in()方法,但我发现它只允许字符串值。

/** @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"}]:使用参数 [{"date":"2020-01-31 00:00:00.000000","timezone_type":3,"timezone":"Europe/Berlin"} 执行“SELECT [...]”时发生异常]:
Catchable Fatal Error: Object of class DateTimeImmutable could not be converted to string可捕获的致命错误:无法将 DateTimeImmutable 类的对象转换为字符串

Is there any easy equivalent of in() function working with dates ?是否有任何简单的in()函数可以处理日期? (preferably not using DQL) (最好不要使用 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.这是我想出的解决方案,循环遍历 PHP 数组,构建另一个eq()表达式数组,然后or一切。 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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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