Setting a Doctrine query limit in Sensio Lab’s Symfony PHP framework for customer queries in respositories

Here is an example of a simple DQL query in a custom repository method meant to return a single array result. The following will return the latest result in case there are multiple contact records that match the “customerId” field, which is actually “customer_id” in the database, but remember that camelCase convention applies to Doctrine mappings of database fields.

// inside entity repository is the getMostRecentContact() method which is called on from any controller that has initialized this repository

function getMostRecentContact($customerId){


   $dql="SELECT $fields FROM \Main\DefaultBundle\Entity\Contact c 
         WHERE c.customerId=$customerId AND c.status='Active' ORDER by c.createdAt DESC";

   $contactArr=$this->_em->createQuery($dql)->setMaxResults(1) ->getArrayResult();

   return $contactArr;
Note: Using Symfony's built-in repository method findBy() is possible here, but with multiple "WHERE" conditions, this approach is usually more flexible.

About Author:

Senior Cloud Software Engineer and 25+ years experienced video production, video editing and 3D animation services for a variety of global clients including local video production here in Jacksonville, Florida.

Leave a Comment

Your email address will not be published. Required fields are marked *