在学说2中selectdate之间的条目

我会疯狂与这个最小的错误,我没有得到解决。 我想select两天之间的条目,下面的例子ilustrate我所有的失败:

select1。

$qb->where('e.fecha > ' . $monday->format('Ym-d')); $qb->andWhere('e.fecha < ' . $sunday->format('Ym-d')); 

结果(0项):

 SELECT r0_.id_reservacion AS id_reservacion0, r0_.fecha AS fecha1, r0_.cliente AS cliente2 FROM reservacion r0_ WHERE (r0_.fecha > 2012 - 07 - 16) AND (r0_.fecha < 2012 - 07 - 22) 

select2

 $qb->add('where', 'e.fecha between 2012-01-01 and 2012-10-10'); 

结果(0项):

 SELECT r0_.id_reservacion AS id_reservacion0, r0_.fecha AS fecha1, r0_.cliente AS cliente2 FROM reservacion r0_ WHERE r0_.fecha BETWEEN 2012 - 01 - 01 AND 2012 - 10 - 10 

这是我目前的条目:

 id fecha cliente 1 2012-07-16 00:00:00 2 2 2012-07-16 13:00:00 4 3 2012-07-22 23:00:00 4 

编辑1

为了评估sql以避免疑惑,我运行了这个查询:

 $qb->where('e.fecha > ' . $sunday->format('Ym-d')); 

结果(3项):

 SELECT r0_.id_reservacion AS id_reservacion0, r0_.fecha AS fecha1, r0_.cliente AS cliente2 

所以,看起来像SQL不是问题。 FROM reservacion r0_ WHERE r0_.fecha> 2012 – 07

你可以做…

 $qb->where('e.fecha BETWEEN :monday AND :sunday') ->setParameter('monday', $monday->format('Ym-d')) ->setParameter('sunday', $sunday->format('Ym-d')); 

要么…

 $qb->where('e.fecha > :monday') ->andWhere('e.fecha < :sunday') ->setParameter('monday', $monday->format('Ym-d')) ->setParameter('sunday', $sunday->format('Ym-d')); 

我相信这样做的正确方法是使用查询生成器expression式:

 $now = new DateTime(); $thirtyDaysAgo = $now->sub(new \DateInterval("P30D")); $qb->select('e') ->from('Entity','e') ->add('where', $qb->expr()->between( 'e.datefield', ':from', ':to' ) ) ->setParameters(array('from' => $thirtyDaysAgo, 'to' => $now)); 

http://docs.doctrine-project.org/en/latest/reference/query-builder.html#the-expr-class

编辑:这种方法相对于其他任何答案的优点是它是独立的数据库软件 – 你应该让Doctrine处理datetypes,因为它有一个处理这种事情的抽象层。

例如,如果您以“Ymd”的forms添加stringvariables,那么当它转到除MySQL以外的数据库平台时,将会中断。


    编辑:看到更好的解决scheme的其他答案

我提供的原始新手方法是(opt1):

 $qb->where("e.fecha > '" . $monday->format('Ym-d') . "'"); $qb->andWhere("e.fecha < '" . $sunday->format('Ym-d') . "'"); 

和(opt2):

 $qb->add('where', "e.fecha between '2012-01-01' and '2012-10-10'"); 

这很快捷,并立即得到原来的海报。

因此,接受的答案。

根据评论,这是错误的答案,但这是一个很容易犯的错误,所以我把它留在这里作为“不该做的事情”。

看看我如何格式化我的date$ jour参数。 这取决于你是否使用expr() – > like或者expr() – > lte

 $qb ->select('e') ->from('LdbPlanningBundle:EventEntity', 'e') ->where( $qb->expr()->andX( $qb->expr()->orX( $qb->expr()->like('e.start', ':jour1'), $qb->expr()->like('e.end', ':jour1'), $qb->expr()->andX( $qb->expr()->lte('e.start', ':jour2'), $qb->expr()->gte('e.end', ':jour2') ) ), $qb->expr()->eq('e.user', ':user') ) ) ->andWhere('e.user = :user ') ->setParameter('user', $user) ->setParameter('jour1', '%'.$jour->format('Ym-d').'%') ->setParameter('jour2', $jour->format('Ym-d')) ->getQuery() ->getArrayResult() ;