This question already has answers here:
Error with a Symfony query : Expected Literal, got '"'
                                
                                    (3个答案)
                                
                        
                                去年关闭。
            
                    
这是我的功能:

  public function findByIdJoinedToCategory($id)
     {
         $query = $this->getEntityManager()
             ->createQuery(
                 'SELECT a, b
                 FROM App\Entity\Products a
                 JOIN a.productgroup b
                 WHERE a.id = 2');
     }


我只是尝试用变量2替换$id。但是我没有成功:

  public function findByIdJoinedToCategory($id)
     {
         $query = $this->getEntityManager()
             ->createQuery(
                 'SELECT a, b
                 FROM App\Entity\Products a
                 JOIN a.productgroup b
                 WHERE a.id = $id');
     }


我收到错误消息:


  [语法错误]第0行,第125行:错误:预期字面量为'$'

最佳答案

简而言之,当在字符串中放置特殊字符(例如换行符或var)时,您需要使用双引号。

要将var放入字符串中,您需要将其串联到字符串中,如下所示:

'SELECT a, b
FROM App\Entity\Products a
JOIN a.productgroup b
WHERE a.id = '.$id


您可以将var放在字符串中,如下所示:

"SELECT a, b
FROM App\Entity\Products a
JOIN a.productgroup b
WHERE a.id = $id"


但是,您可能会发现以下内容更具可读性:

"SELECT a, b
FROM App\Entity\Products a
JOIN a.productgroup b
WHERE a.id = {$id}"

关于jquery - 如何在mysql查询中使用变量? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54113175/

10-10 19:20