簡體   English   中英

帶有日期的 in() 表達式的等價原則

[英]Doctrine equivalent of in() expression with dates

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

使用參數 [{"date":"2020-01-31 00:00:00.000000","timezone_type":3,"timezone":"Europe/Berlin"} 執行“SELECT [...]”時發生異常]:
可捕獲的致命錯誤:無法將 DateTimeImmutable 類的對象轉換為字符串

是否有任何簡單的in()函數可以處理日期? (最好不要使用 DQL)

這是我想出的解決方案,循環遍歷 PHP 數組,構建另一個eq()表達式數組,然后or一切。 它完成了它的工作,但需要在數組中為每個日期聲明一個參數,而不是一個單一的數組參數。

如果您找到更好的方法,請告訴我...

/** @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