Symfony2 Select one column in doctrine

34,180

Solution 1

Since you are requesting single column of each record you are bound to expect an array. That being said you should replace getResult with getArrayResult() because you can't enforce object hydration:

$data = $qb->getArrayResult();
Now, you have structure:
    $data[0]['address']
    $data[1]['address']
    ....

Hope this helps.

As for the discussion about performance in comments I generally agree with you for not wanting all 30 column fetch every time. However, in that case, you should consider writing named queries in order to minimize impact if you database ever gets altered.

Solution 2

You can use partial objects to only hydrate one field and still return a object.

Solution 3

This worked for me:

  $qb = $repository->createQueryBuilder('i')
    ->select('i.name')
    ->...

Solution 4

Use partial objects like this to select fields

$qb = $this->createQueryBuilder('r')
    ->select(array('partial r.{id,address}'))
    ...

Put your field names between the brackets

Share:
34,180
Lughino
Author by

Lughino

Always passionate about of computing and solving logic problems. In recent years I have gained experience in leadership in medium sized team. From the development side, I discovered a love for the MEAN stack, where the coupled javascript server side and NoSQL technologies have been adopted in all my projects.

Updated on December 16, 2020

Comments

  • Lughino
    Lughino over 3 years

    I'm trying to refine the query trying to select fewer possible values ​​.. For example I have an entity "Anagrafic" that contains your name, address, city, etc., and a form where I want to change only one of these fields, such as address. I have created this query:

    //AnagraficRepository
    public function findAddress($Id)
    {
         $qb = $this->createQueryBuilder('r')
                 ->select('r.address')
                 ->where('r.id = :id')
                 ->setParameter('id', $Id)
                 ->getQuery();
    
         return $qb->getResult();
    }
    

    there is something wrong with this query because I do not return any value, but if I do the query normally:

    //Controller
    $entity = $em->getRepository('MyBusinessBundle:Anagrafic')->find($id);
    

    Return the right value. How do I do a query selecting only one column?