投放到querybuilder

时间:2018-07-16 12:28:52

标签: php postgresql symfony-2.6

我有一个这样的querybuilder:

        ->andWhere('i.createdAt LIKE :date')
        ->setParameter('date', $date.'%')

字段created_at是DateTime,而我的$ date是字符串。 有什么方法可以将我的created_at强制转换为字符串?

我已经尝试过:

            ->andWhere('i.createdAt::text LIKE :date')

控制台:

.... has no field or association named createdAt::text

或:

            ->andWhere('to_char(i.createdAt) LIKE :date')

控制台:

  [Syntax Error] line 0, col 208: Error: Expected known function, got 'to_char'

  [Syntax Error] line 0, col 208: Error: Expected known function, got 'cast'

我正在使用Symfony 2.6和postgreSQL。

谢谢:)

2 个答案:

答案 0 :(得分:0)

将日期格式设置为类似这样的字符串:

$date->format('Y-m-d H:i:s')

或者因为它是LIKE查询而忽略了日期和时间

$date->format('Y-m-') . '%'

但是请考虑在起点和终点之间查询日期:

$nextMonth = clone $date;
$nextMonth->modify('+1 month');

然后您可以将大于或等于第一个日期,小于或等于结束日期

答案 1 :(得分:0)

谢谢你,这是个好主意。

    $startInterval = \DateTime::createFromFormat('Y-m', $date);
    $endInterval = clone $startInterval;
    $endInterval->modify('+1 month'); 

这是更好的方法!

        ->andWhere('i.createdAt > :startInterval')
        ->andWhere('i.createdAt < :endInterval')
        ->setParameter('startInterval', $startInterval)
        ->setParameter('endInterval', $endInterval)