Symfony 和 Doctrine 从数据库中提取 ID

Symfony & Doctrine Pulling ID from DB

我正在尝试编写一个函数,该函数在被调用时将 return 最新条目的 ID 放入我的数据库中。我是 PHP 的新手,所以请原谅我糟糕的代码。

public function devicesFunctionAction()
{   
    $em = $this->getDoctrine()->getManager();
    $query = $em->createQuery(
      'SELECT id 
      FROM AppBundle:ZeusUsers
      ORDER BY id DESC');
    $id = $query->getResult();
    $query->setMaxResults(1);

    return new Response(json_encode(array('key' => $id)));
}

上面的代码产生了 500 错误,但它似乎是 'BY' 导致的:

[Syntax Error] line 0, col 48: Error: Expected end of string, got 'BY' (500 Internal Server Error)

阅读 Doctrine 文档后,他们在示例中使用了 'ORDER BY',所以我不明白为什么会导致这样的问题。

任何帮助将不胜感激,如果这还不够,可以轻松提供更多信息。

这不是纯粹的 SQL 除非你使用 $connection->prepare() 和 execute() 否则你不能像这样用 doctrine 来做,但是要回答你的问题,请像这样使用它:

    $em = $this->getDoctrine()->getManager();
    $query = $em->createQuery(
      'SELECT z.id
      FROM AppBundle:ZeusUsers z
      ORDER BY z.id DESC');
    $query->setMaxResults(1); // and setMaxResults(1) before getResult() obvisouly :p
    $id = $query->getSingleScalarResult();

已编辑。