35

I'm using Doctrine createQueryBuilder() to construct queries in Symfony2. But, I don't want to take all columns in this entity. How can I select only the ID and Name?

$query = $this->getEntityManager()->createQueryBuilder();
        $query
            ->select('d')
            ->from('AcmeBundle:Demo', 'd')
            ->leftjoin('d.otherEntity', 'o');

        $query->setMaxResults(10);
        $results = $query->getQuery()->getResult();

Thank you so much,

AppyGG
  • 381
  • 1
  • 6
  • 12

1 Answers1

70

Try following,

$fields = array('d.id', 'd.name', 'o.id');
//$fields = 'partial d.{id, name}, partial o.{id}';  //if you want to get entity object

$query = $this->getEntityManager()->createQueryBuilder();
$query
    ->select($fields)
    ->from('AcmeBundle:Demo', 'd')
    ->leftjoin('d.otherEntity', 'o');

$query->setMaxResults(10);
$results = $query->getQuery()->getResult();
Ondrej Slinták
  • 31,386
  • 20
  • 94
  • 126
Mun Mun Das
  • 14,992
  • 2
  • 44
  • 43
  • will it hydrate query result ? – hardik Jul 18 '14 at 09:45
  • is there a way to set the fields from setParameter ? – Vamsi Krishna B Jul 27 '15 at 07:24
  • `partial alias.{comma, fields}` is not working to me on symfony 2.4. Should it work or is it only for newer versions? – Vandervals May 31 '18 at 11:34
  • @hardik see "Hydration Modes" here https://www.doctrine-project.org/projects/doctrine-orm/en/2.9/reference/dql-doctrine-query-language.html#hydration-modes – Nadim Nov 23 '21 at 17:30
  • 1
    @Vandervals Doctrine version 2.10 or greater. See https://www.doctrine-project.org/projects/doctrine-orm/en/2.10/reference/partial-objects.html#partial-objects – Nadim Nov 23 '21 at 17:32
  • I think it's also worth mentioning that it's required to include "_identifier/primary key column name_" in the columns list for all the entities (e.g., `id` for both `d` and `o` in `partial d.{id, name}, partial o.{id}`) while using the `partial` keyword to get the join's primary entity object (e.g.,`d`) instance mapped with the partial result set. – Sivaram Koduri Dec 21 '21 at 18:43
  • this solution does not work with **distinct**: `$qb->distinct('d.id, d.name')`. To make it work need to change it to this `$qb->select('DISTINCT d.id, d.name')` – Nuryagdy Mustapayev Jul 21 '22 at 13:53