案例不在doctrine查询构建器中的子句

时间:2017-05-10 10:55:22

标签: mysql symfony doctrine-orm doctrine symfony-2.8

我在doctrine的where子句中遇到了mysql CASE的问题,

 $rides_q1 = $em->getRepository('IRRideBundle:Ride');
    $query = $rides_q1->createQueryBuilder('a')
                     ->where('(CASE WHEN a.ephemeral = 1 THEN a.date_beginning < NOW() AND a.date_ending > NOW()ELSE a.ephemeral = 0 END) AND a.active = 1 AND a.status = 5')                  
     ->getQuery();
$ridesQuery = $query->execute();



**[Syntax Error] line 0, col 93: Error: Expected Doctrine\ORM\Query\Lexer::T_ELSE, got '<'**

[2/2] QueryException: [Syntax Error] line 0, col 93: Error: Expected Doctrine\ORM\Query\Lexer::T_ELSE, got '<'   +
[1/2] QueryException: SELECT a FROM IR\RideBundle\Entity\Ride a WHERE (CASE WHEN ephemeral = 1 THEN date_beginning < NOW() AND date_ending > NOW()ELSE ephemeral = 0 END) 

我想准备这个sql查询,它与phpmyadmin一起工作正常

SELECT * FROM ride WHERE (CASE WHEN ephemeral = 1 THEN date_beginning < NOW() AND date_ending > NOW()ELSE ephemeral = 0 END) AND active = 1 AND `status_id` = 5 ORDER BY `date_ending` DESC

2 个答案:

答案 0 :(得分:1)

CASE中的WHERE表达式错误。您可以将其转换为正常的复合条件,如

(CASE WHEN a.ephemeral = 1 THEN a.date_beginning < NOW() AND a.date_ending > NOW()ELSE a.ephemeral = 0 END)

SELECT * FROM ride
WHERE ((a.ephemeral = 1 
       and a.date_beginning < NOW() 
       AND a.date_ending > NOW()) 
  OR a.ephemeral = 0)
  AND a.active = 1 
  AND a.status = 5
ORDER BY `date_ending` DESC

答案 1 :(得分:0)

当您需要使用Doctrine构建Query时使用的方法createQueryBuilder()。 例如:

 public function findPostsQuery()
  {
      $qb = $this->createQueryBuilder('p');
      $qb
          ->where('p.postStatus = :postStatus')
          ->orderBy('p.id', 'DESC')
          ->setParameter('postStatus', true);
      return $qb->getQuery();
  } 


如果您不创建自定义查询 - 请使用createQuery()方法。 例如:

 $em = $this->getDoctrine()->getManager();
 $query = $em->createQuery(
     'SELECT p
     FROM AppBundle:Product p
     WHERE p.price > :price
     ORDER BY p.price ASC'
 )->setParameter('price', 19.99);

 $products = $query->getResult();

官方documentation帮助您