简体   繁体   中英

Symfony & Doctrine Pulling ID from DB

I'm trying to write a function that when called will return the ID of the latest entry into my DB. I'm fairly new to PHP so please forgive me for my poor code.

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)));
}

The above code produces a 500 error however it seems to be the 'BY' causing this:

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

After reading the Doctrine documentation they use 'ORDER BY' in their example so I can't understand why it is causing such a issue.

Any help would be greatly appreciated, can easily provide more info if this is not enough.

This is not pure SQL you cannot do it like this with doctrine unless you use $connection->prepare() and execute() but to answer your question use it like this :

    $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();

EDITED.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM