How to fetch class instead of array in Doctrine 2

浪尽此生 提交于 2019-11-28 07:37:16

Yes you can, usually using:

$repository
    ->createQueryBuilder('p')
    ->getQuery()
    ->execute()
;

This should return you an array of entities.

If you want to get a single entity result, use either getSingleResult or getOneOrNullResult:

$repository
    ->createQueryBuilder('p')
    ->getQuery()
    ->getOneOrNullResult()
;

Warning: These method can potentially throw NonUniqueResultException.

Edit: Ok, so the question was about partial objects: http://docs.doctrine-project.org/en/latest/reference/partial-objects.html

you can get an object instead of array by using "Partial Objects".

here is a tested example with DoctrineORM 2.2.2:

// create query builder
// $em is the EntityManager
$qb    = $em->createQueryBuilder();

// specify the fields to fetch (unselected fields will have a null value)
$qb->select  ('partial p.{id,pubDate,title,summary}')
   ->from    ('Project\Entity\Post', 'p')
   ->where   ('p.isActive = 1')
   ->orderBy ('p.pubDate', 'desc');

$q      = $qb->getQuery();

$result = $q->getResult();
var_dump($result); // => object

If you wish to return an object from your original query:

    $product->createQueryBuilder('p')
    ->setMaxResults(1)
    ->where('p.idx = :idx')
    ->select('p.columnNameHere')
    ->setParameter('idx', 8081)
    ->orderBy('p.idx', 'DESC')
    ->getQuery();
    $product = $query->getResult();

Remove this line

->select('p.columnNameHere')

As soon as you use select, it will return an array...

getResult() method returns a collection (an array) of entities. Use getSingleResult() if you're going to fetch only one object.

EDIT:

Oh, I just noticed that you want to fetch a single field of a single object. Use getSingleScalarResult() as @Florian suggests.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!