问题
I have the following query: (it works fine without the addSelect('CASE ... END AS HIDDEN loquer') part which goals is to add some order into my comments. but with this part the following message from symfony is triggered: Error: Expected Literal, got '"'
public function myfindArticleandCommentsandScores($article,$language){
$qb = $this->createQueryBuilder('a');
$qb->leftjoin('a.comments','c')
->addSelect('c')
->leftJoin('c.scores','s')
->addSelect('s')
->leftJoin('s.user','u')
->addSelect('u')
->addSelect('
CASE
WHEN c.show = "yes" THEN 1 // PROBLEME IS HERE
ELSE 2
END AS HIDDEN show_order
')
->where(
$qb->expr()->eq('a.id', '?1'),
$qb->expr()->orX(
$qb->expr()->eq('c.langue', '?2'),
$qb->expr()->eq('c.langue', '?3')
)
)
->setParameters(array(
'1'=> $article,
'2'=> $language,
'3'=> 'EN',
))
->orderBy('show_order', 'ASC')
->addOrderBy('c.scorenote', 'DESC');
return $qb->getQuery()
->getResult();
}
I tried to replace "yes" with 'yes' but then I got the following message: FatalErrorException: Parse: syntax error, unexpected 'oui' (T_STRING)
回答1:
Use setParameter to replace a placeholder with a string or use
"xyz='yes'"
Now what the code should looks like (one possible way):
public function myfindArticleandCommentsandScores($article,$language){
$qb = $this->createQueryBuilder('a');
$qb->leftjoin('a.comments','c')
->addSelect('c')
->leftJoin('c.scores','s')
->addSelect('s')
->leftJoin('s.user','u')
->addSelect('u')
->addSelect('
CASE
WHEN c.show = \'yes\' THEN 1 // PROBLEME IS HERE
ELSE 2
END AS HIDDEN show_order
')
->where(
$qb->expr()->eq('a.id', '?1'),
$qb->expr()->orX(
$qb->expr()->eq('c.langue', '?2'),
$qb->expr()->eq('c.langue', '?3')
)
)
->setParameters(array(
'1'=> $article,
'2'=> $language,
'3'=> 'EN',
))
->orderBy('show_order', 'ASC')
->addOrderBy('c.scorenote', 'DESC');
return $qb->getQuery()
->getResult();
}
回答2:
String delimiters in DQL should be avoided where possible.
->addSelect('
CASE
WHEN c.show = :show THEN 1
ELSE 2
END AS HIDDEN show_order
')
->setParameter('show', 'yes')
回答3:
I added a parameter just like this:
->addSelect('
CASE
WHEN t.loquage = :show_first THEN 1
ELSE 2
END AS HIDDEN loquer
')
->setParameters(array(
'show_first'=> 'oui',
thanks to Qoop who helped me.
来源:https://stackoverflow.com/questions/30894291/symfony-query-error-expected-literal-got