案例在学说查询生成器 where 子句中不起作用

Case not work in doctrine query builder where clause

我在 mysql CASE 的 where 条文中遇到问题,

 $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

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

(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

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

 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帮你