我面临着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 DoctrineORMQueryLexer::T_ELSE, got '<'**
[2/2] QueryException: [Syntax Error] line 0, col 93: Error: Expected DoctrineORMQueryLexer::T_ELSE, got '<' +
[1/2] QueryException: SELECT a FROM IRRideBundleEntityRide 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()
当你需要用原则构建查询时使用。例如:
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();
官方文档可帮助您