8

我正在尝试优化查询,尝试选择更少的可能值。例如,我有一个实体“Anagrafic”,其中包含您的姓名、地址、城市等,以及一个我只想更改其中一个的表单这些字段,例如地址。我创建了这个查询:

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

     return $qb->getResult();
}

这个查询有问题,因为我没有返回任何值,但是如果我正常进行查询:

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

返回正确的值。如何只选择一列进行查询?

4

4 回答 4

16

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.

于 2013-02-24T00:56:03.080 回答
8

您可以使用部分对象仅水合一个字段并仍然返回一个对象。

于 2013-02-24T01:11:25.180 回答
3

这对我有用:

  $qb = $repository->createQueryBuilder('i')
    ->select('i.name')
    ->...
于 2014-10-10T11:05:52.653 回答
2

使用像这样的部分对象来选择字段

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

将您的字段名称放在括号之间

于 2014-10-07T16:34:40.477 回答