Symfony2中的本机查询问题

时间:2014-09-04 02:47:59

标签: symfony doctrine-orm symfony-2.3

那里,我试图在Symfony2中执行本机MySQL查询,但是我得到一个SQL错误,这是原始查询:

$sql= "SELECT s.id_tariffs_key,s.description,s.voice_rate
  FROM tariffs s
  JOIN (SELECT MAX(id_tariffs_key) AS id FROM tariffs GROUP BY description) max
  ON s.id_tariffs_key = max.id
  WHERE s.description like '$letter%' and s.description not like '%-%'";

这是Symfony2的查询:

$rsm = new ResultSetMapping;
  $rsm->addEntityResult('MyBundle:Tariffs', 't');

  $query = $this->getEntityManager()->createNativeQuery("SELECT t.id_tariffs_key,t.description,t.voice_rate FROM tariffs 
      JOIN (SELECT MAX(t.id_tariffs_key) AS id FROM tariffs GROUP BY t.description) max ON id_tariffs_key = max.id 
       t.description like '?%' and t.description not like '%-%'", $rsm);
  $query->setParameter(1, $letter);

当我尝试加载页面时,它说:

An exception occurred while executing 'SELECT t.id_tariffs_key,t.description,t.voice_rate FROM tariffs 
JOIN (SELECT MAX(t.id_tariffs_key) AS id FROM tariffs GROUP BY description) max ON id_tariffs_key = max.id 
t.description like '?%' and t.description not like '%-%'' with params [23]:

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 't.description like '?%' and t.description not like '%-%'' at line 3

请帮忙吗?

谢谢!

1 个答案:

答案 0 :(得分:1)

您将查询翻译成Doctrine时严重损坏了查询,包括忘记WHERE语句。

这是我的Doctrine查询的固定版本

$query = $this->getEntityManager()->createNativeQuery(
    "SELECT t.id_tariffs_key, t.description, t.voice_rate
    FROM tariffs t
    JOIN (
        SELECT MAX(id_tariffs_key) AS id
        FROM tariffs
        GROUP BY description
    ) max ON id_tariffs_key = max.id
    WHERE t.description LIKE ? AND t.description NOT LIKE '%-%'",
    $rsm);
$query->setParameter(1, $letter.'%');