在Doctrine2中的本机查询中获取未映射的字段 [英] Get an unmapped field in a native query in Doctrine2

查看:69
本文介绍了在Doctrine2中的本机查询中获取未映射的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Symfony3中使用了Doctrine2,该函数使用经度和纬度搜索最近的伙伴:

I have a function in Symfony3 with Doctrine2 which is searching for the nearest partner, using latitude and longitude:

public function findNearestPartner($lat,$lng) {

    $rsm=new ResultSetMappingBuilder($this->_em);
    $rsm->addRootEntityFromClassMetadata('AppBundle\Entity\Partner','p');

    $sqlQuery="SELECT p.*, (6371 * acos(cos(radians(:lat)) * cos(radians(p.latitude)) * cos(radians(p.longitude) - radians(:lng)) + sin(radians(:lat)) * sin(radians(p.latitude)))) AS distance
    FROM sp_partner p
    ORDER BY distance ASC
    LIMIT 0,1";

    $query=$this->_em
        ->createNativeQuery($sqlQuery,$rsm)
        ->setParameter('lat',$lat)
        ->setParameter('lng',$lng)
    ;

    return $query->getOneOrNullResult();
}

如您所见,我得到了最近的合作伙伴实体-但是有还有距离字段,我不会退缩(但这将非常有用)。有什么方法可以获取该字段的值?
我在文档中阅读了( http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/native-sql.html ),但在这种情况下我找不到有用的东西。

As you see, I get the nearest Partner-Entity back - but there is also the field "distance", which I don't get back (but it would be very useful). Is there any way to get the value of this field? I read in the docu (http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/native-sql.html), but I can't find anything useful for this case.

推荐答案

您可以通过 addScalarResult 来实现。

$rsm=new ResultSetMappingBuilder($this->_em);
$rsm->addRootEntityFromClassMetadata('AppBundle\Entity\Partner','p');
$rsm->addScalarResult('distance', 'distance');

结果将是

array:2 [▼
  0 => Partner{...},
  distance => xxx
]

这篇关于在Doctrine2中的本机查询中获取未映射的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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