Symfony2 在学说中选择一列 [英] Symfony2 Select one column in doctrine

查看:20
本文介绍了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?

推荐答案

由于您请求每条记录的单列,因此您必然需要一个 array.话虽如此,您应该将 getResult 替换为 getArrayResult(),因为您无法强制对象水合:

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天全站免登陆