Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expected end of string, got 'LIMIT' when using LIMIT in DQL Symfony

I need to get the last Id from my table so i can use it in another function i created this function on my repository but i didn't work it show me an error:

[Syntax Error] line 0, col 60: Error: Expected end of string, got 'LIMIT'

the function i'am using :

         public function LastIdCart()
          {
            $query = $this->getEntityManager()
            ->createQuery("select i.id from BoutiqueBundle:Panier i ORDER BY 
            i.id DESC LIMIT 1");
            return $query->getResult();
           }
like image 246
Slim.aouadi Avatar asked Dec 08 '25 17:12

Slim.aouadi


2 Answers

class YourController extends Controller {

     *********************************************************
     public function yourAction( *** ) {
          $youLastRecord = $this->getDoctrine()->getRepository(YourEntity::class)->findOneBy(
               array(),
               array('id' => 'DESC')
          );
     }
}
like image 131
Imanali Mamadiev Avatar answered Dec 10 '25 10:12

Imanali Mamadiev


The correct way to use OFFSET and/or LIMIT with a DQL Query is using the following api on the $query object as follow:

Query::setMaxResults($maxResults)
Query::setFirstResult($offset)

As describe in the doc First and Max Result Items (DQL Query Only)

As example, your code should be like:

     public function LastIdCart()
      {
        $query = $this->getEntityManager()
        ->createQuery("select i.id from BoutiqueBundle:Panier i ORDER BY 
        i.id");
         $query->setMaxResults(1);
        return $query->getResult(); // will return an arraycollection with only one element
       }

Hope this clarify

like image 42
Matteo Avatar answered Dec 10 '25 09:12

Matteo