Symfony2在教义中选择一列 [英] Symfony2 Select one column in doctrine

查看:213
本文介绍了Symfony2在教义中选择一列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

推荐答案

由于您要求每个记录的单列一定会期待一个数组。这就是说,您应该使用 getArrayResult()替换 getResult ,因为您无法强制实施对象水合:

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']
    ....

希望这有帮助。

关于在评论中表现的讨论,我一般都同意您的意见,因为每次都不希望全部30列提取。但是,在这种情况下,您应该考虑编写命名查询,以便最小化影响,如果数据库被更改。

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.

这篇关于Symfony2在教义中选择一列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆