Case not work in doctrine query builder where clau

2019-09-09 19:59发布

I am facing issue with mysql CASE in where clause of doctrine,

 $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) 

I want to prepare this sql query, its working fine with 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条回答
姐就是有狂的资本
2楼-- · 2019-09-09 20:58

Method createQueryBuilder() used when you need build Query with Doctrine. For example:

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


If you wont create Custom query - use createQuery() method. For example:

 $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();

Official documentation help you

查看更多
霸刀☆藐视天下
3楼-- · 2019-09-09 21:05

Your CASE expression in WHERE is wrong. You could convert it to normal compound condition like

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

To

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
查看更多
登录 后发表回答